卖萌的弱渣

I am stupid, I am hungry.

Palindrome Linked List

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?

Solution

  • Use fast and slow point, then find the middle of the list
  • Reverse right half and compare the left half and right half
(Palindrome-Linked-List.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return True

        dummy = ListNode(-1)
        dummy.next = head
        # find the mid
        slow = dummy
        fast = dummy

        while fast != None and fast.next != None:
            slow = slow.next
            fast = fast.next.next
        mid = slow.next
        slow.next = None

        # reverse the right half
        start = mid
        end = mid.next
        start.next = None
        while end != None:
            tmp = end.next
            end.next = start
            start = end
            end = tmp

        # compare the left half and right half
        right_head = start
        left_head = head

        while right_head != None and left_head != None:
            if right_head.val != left_head.val:
                return False
            right_head = right_head.next
            left_head = left_head.next
        return True