-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path234.py
More file actions
66 lines (47 loc) · 1.45 KB
/
234.py
File metadata and controls
66 lines (47 loc) · 1.45 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# 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 reverse(self, midPtr, prevPtr):
while midPtr:
currPtr = midPtr
nextPtr = currPtr.next
currPtr.next = prevPtr
prevPtr = currPtr
midPtr = nextPtr
return prevPtr
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slowPtr, fastPtr = head, head
tempHead = head
while fastPtr:
if fastPtr.next and fastPtr.next.next:
fastPtr = fastPtr.next.next
slowPtr = slowPtr.next
elif fastPtr.next:
fastPtr = fastPtr.next
slowPtr = slowPtr.next
else:
break
## Reverse the linked list from fastPtr to slowPtr
tempNode = self.reverse(slowPtr.next, slowPtr)
slowPtr.next = None
while tempNode and tempNode:
if tempHead.val != tempNode.val:
return False
tempHead = tempHead.next
tempNode = tempNode.next
return True
if __name__ == '__main__':
s = Solution()
t = ListNode(1)
t.next = ListNode(2)
t.next.next = ListNode(2)
t.next.next.next = ListNode(1)
# t.next.next.next.next = ListNode(1)
print(s.isPalindrome(t))