forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234.palindrome-linked-list.py
54 lines (41 loc) · 1.17 KB
/
234.palindrome-linked-list.py
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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
cur = head.next
head.next = None
while (cur is not None):
next = cur.next
cur.next = head.next
head.next = cur
cur = next
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
newHead = ListNode(0)
newHead.next = head
slow = newHead
fast = newHead
# find middle
while (fast is not None and fast.next is not None):
slow = slow.next
fast = fast.next.next
# reverse later half
self.reverseList(slow)
left = head
right = slow.next
result = True
while (left is not None and right is not None):
if left.val != right.val:
result = False
break
left = left.next
right = right.next
# reverse it back
# self.reverseList(slow)
return result