File tree 1 file changed +78
-0
lines changed
1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ # -*- coding: utf-8 -*-
2
+ # @Time : 2019/3/4 10:55
3
+ # @Author : xulzee
4
+
5
+ # @File : 234. Palindrome Linked List.py
6
+ # @Software: PyCharm
7
+
8
+ # Definition for singly-linked list.
9
+ class ListNode :
10
+ def __init__ (self , x ):
11
+ self .val = x
12
+ self .next = None
13
+
14
+
15
+ class Solution :
16
+ def reverseList (self , head : ListNode ) -> bool :
17
+ if head == None or head .next == None :
18
+ return head
19
+
20
+ t = self .reverseList (head .next )
21
+
22
+ head .next .next = head
23
+ head .next = None
24
+
25
+ return t
26
+
27
+ def isPalindrome (self , head : ListNode ) -> bool :
28
+ if head == None or head .next == None :
29
+ return True
30
+ slow = head
31
+ fast = head
32
+ while fast .next != None and fast .next .next != None :
33
+ slow = slow .next
34
+ fast = fast .next .next
35
+
36
+ if fast .next != None :
37
+ slow = slow .next
38
+
39
+ slow = self .reverseList (slow )
40
+
41
+ while slow != None :
42
+ if head .val != slow .val :
43
+ return False
44
+ head = head .next
45
+ slow = slow .next
46
+ return True
47
+
48
+
49
+
50
+ def stringToListNode (numbers ):
51
+
52
+ # Now convert that list into linked list
53
+ dummyRoot = ListNode (0 )
54
+ ptr = dummyRoot
55
+ for number in numbers :
56
+ ptr .next = ListNode (number )
57
+ ptr = ptr .next
58
+
59
+ ptr = dummyRoot .next
60
+ return ptr
61
+
62
+
63
+ def main ():
64
+ while True :
65
+ try :
66
+ line = [1 ,0 ,1 ]
67
+ head = stringToListNode (line );
68
+
69
+ ret = Solution ().isPalindrome (head )
70
+
71
+ out = (ret );
72
+ print (out )
73
+ except StopIteration :
74
+ break
75
+
76
+
77
+ if __name__ == '__main__' :
78
+ main ()
You can’t perform that action at this time.
0 commit comments