lc234. Palindrome Linked List

130 阅读1分钟

234. Palindrome Linked List

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

Example 1:

Input: 1->2 Output: false Example 2:

Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space?

思路:找到链表中间位置,把后面一部分链表翻转,然后从头开始比较两个链表

代码:python3

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        fast=slow=head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        node = None
        while slow:
            pre = slow
            slow = slow.next
            pre.next = node
            node = pre

        while node:
            if node.val!=head.val:
                return False
            node = node.next
            head = head.next
        return True