forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0234.py
60 lines (50 loc) · 1.24 KB
/
0234.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
55
56
57
58
59
60
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None or head.next == None:
return True
lat = head.next
pre = head
while lat != None and lat.next != None:
lat = lat.next.next
pre = pre.next
cur = pre.next
pre.next = None
p = None
while cur != None:
q = cur.next
cur.next = p
p = cur
cur = q
while p != None and head != None:
if p.val != head.val:
return False
p = p.next
head = head.next
return True
def createList():
head = ListNode(0)
cur = head
for i in range(1, 3):
cur.next = ListNode(i)
cur = cur.next
return head
def printList(head):
cur = head
while cur != None:
print(cur.val, '-->', end='')
cur = cur.next
print('NULL')
if __name__ == "__main__":
head = createList()
printList(head)
res = Solution().isPalindrome(head)
print(res)