234. 回文链表


官方链接

https://leetcode-cn.com/problems/palindrome-linked-list/submissions/

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解法一 快慢指针,前半段反转

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {

        if (head == null || head.next == null) return true;

        ListNode pre = head, slow = head, fast = head, prepre = null;
        while(fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;

            pre.next = prepre;
            prepre = pre;
        }
        if (fast != null) slow = slow.next;

        while (pre != null) { // pre != null && slow != null
            if (pre.val != slow.val) return false;
            slow = slow.next;
            pre = pre.next;
        }

        return true;
    }
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if head == None or head.next == None:
            return True
        pre = slow = fast = head
        prepre = None
        while fast != None and fast.next != None:
            pre = slow
            slow, fast = slow.next, fast.next.next
            pre.next = prepre
            prepre = pre

        if fast != None:
            slow = slow.next

        while pre != None and slow != None:
            if pre.val != slow.val:
                return False
            slow = slow.next
            pre = pre.next

        return True