-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path234. Palindrome Linked List.py
More file actions
78 lines (57 loc) · 1.62 KB
/
234. Palindrome Linked List.py
File metadata and controls
78 lines (57 loc) · 1.62 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
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
# @Time : 2019/3/4 10:55
# @Author : xulzee
# @Email : xulzee@163.com
# @File : 234. Palindrome Linked List.py
# @Software: PyCharm
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> bool:
if head == None or head.next == None :
return head
t = self.reverseList(head.next)
head.next.next = head
head.next = None
return t
def isPalindrome(self, head: ListNode) -> bool:
if head == None or head.next == None:
return True
slow = head
fast = head
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if fast.next != None:
slow = slow.next
slow = self.reverseList(slow)
while slow != None:
if head.val != slow.val:
return False
head = head.next
slow = slow.next
return True
def stringToListNode(numbers):
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def main():
while True:
try:
line = [1,0,1]
head = stringToListNode(line);
ret = Solution().isPalindrome(head)
out = (ret);
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()