aboutsummaryrefslogtreecommitdiff
path: root/palindrome_linked_list.py
blob: 85c40c3ab23dff11c47b32804ba6313ac7178b71 (plain)
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
# 234. Palindrome Linked List

"""
given the head of a signly linked list return true if it is a palindrome or
false otherwise.
"""


# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow, fast, prev = head, head, None
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        prev, slow, prev.next = slow, slow.next, None
        while slow:
            slow.next, prev, slow = prev, slow, slow.next
        fast, slow = head, prev
        while slow:
            if fast.val != slow.val:
                return False
            fast, slow = fast.next, slow.next
        return True


if __name__ == "__main__":
    obj = Solution()
    h1 = ListNode()
    h2 = ListNode()