LeetCode 234. Palindrome Linked List(对称链表)

原题网址:https://leetcode.com/submissions/detail/58253344/

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

思路:普通的思路是可以生成一个反转的链表,然后两个链表逐个节点比较,时间复杂度O(n),空间复杂度O(1)。如果要求空间复杂度O(1)的话,就只能在原链表上做文章了,因为题目并不禁止我们修改原链表,所以我们可以将原链表拆分为前后两段,将前面的反转,然后再逐个比较两段链表的节点。使用慢指针(每次移动一个节点)和快指针(每次移动两个节点),就能够找到链表的中间节点。

慢指针最后停在的位置,就是前段链表拆分后的链表头,后段链表的链表头,需要根据节点个数是奇数还是偶数会有差异,需要分开处理。

LeetCode 234. Palindrome Linked List(对称链表)_第1张图片


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) return true;
        ListNode slow = head;
        ListNode next = head.next;
        ListNode fast = head.next;
        head.next = null;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;

            ListNode prev = slow;
            slow = next;
            next = next.next;
            slow.next = prev;
        }
        ListNode n1 = slow;
        ListNode n2 = fast.next == null ? next : next.next;
        while (n1 != null) {
            if (n1.val != n2.val) return false;
            n1 = n1.next;
            n2 = n2.next;
        }
        return true;
    }
}

LeetCode 234. Palindrome Linked List(对称链表)_第2张图片

另一个类似的方法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode prev = null;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            ListNode next = slow.next;
            slow.next = prev;
            prev = slow;
            slow = next;
        }
        fast = fast == null ? slow : slow.next;
        slow = prev;
        while (slow != null) {
            if (slow.val != fast.val) return false;
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }
}


你可能感兴趣的:(链表,变形,反转,对称)