File tree Expand file tree Collapse file tree
data-structures/linked-lists Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ def is_palindrome (head ):
2+ if not head :
3+ return True
4+ fast , slow = head .next , head
5+ while fast and fast .next :
6+ fast = fast .next .next
7+ slow = slow .next
8+ second = slow .next
9+ node = None
10+ while second :
11+ nxt = second .next
12+ second .next = node
13+ node = second
14+ second = nxt
15+ while node :
16+ if node .val != head .val :
17+ return False
18+ node = node .next
19+ head = head .next
20+ return True
21+
22+
23+ def is_palindrome_stack (head ):
24+ if not head or not head .next :
25+ return True
26+
27+ # Get the midpoint
28+ slow = fast = cur = head
29+ while fast and fast .next :
30+ fast , slow = fast .next .next , slow .next
31+
32+ # Push the second half into the stack
33+ stack = [slow .val ]
34+ while slow .next :
35+ slow = slow .next
36+ stack .append (slow .val )
37+
38+ # Comparison
39+ while stack :
40+ if stack .pop () != cur .val :
41+ return False
42+ cur = cur .next
43+
44+ return True
45+
46+
47+ def is_palindrome_dict (head ):
48+ if not head or not head .next :
49+ return True
50+ d = {}
51+ pos = 0
52+ while head :
53+ if head .val in d .keys ():
54+ d [head .val ].append (pos )
55+ else :
56+ d [head .val ] = [pos ]
57+ head = head .next
58+ pos += 1
59+ checksum = pos - 1
60+ middle = 0
61+ for v in d .values ():
62+ if len (v ) % 2 != 0 :
63+ middle += 1
64+ else :
65+ step = 0
66+ for i in range (0 , len (v )):
67+ if v [i ] + v [len (v ) - 1 - step ] != checksum :
68+ return False
69+ step += 1
70+ if middle > 1 :
71+ return False
72+ return True
You can’t perform that action at this time.
0 commit comments