-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindrome_ll.py
More file actions
57 lines (42 loc) · 1.47 KB
/
palindrome_ll.py
File metadata and controls
57 lines (42 loc) · 1.47 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
class Node:
def __init__(self, value, next=None):
self.val = value
self.next = next
# first we want to find the middle node.
# once we've found the middle node, we want to reverse the second half of the list
# once we have reversed the list we want to then go back from the middle and compare the start to the middle for each node
# of there's a node with a diff val its not a palindrome
class Solution:
def isPalindrome(self, head):
mid = self.find_mid(head)
reversed_head = self.reverse(mid)
curr = head
curr_reversed = reversed_head
while curr_reversed:
if curr.val != curr_reversed.val:
return False
curr_reversed = curr_reversed.next
curr = curr.next
return True
def reverse(self, head):
prev = None
curr = head
while curr:
next = curr.next # store swapped node for later so we dont overwrite it
curr.next = prev # reverse the link
prev = curr # move prev forward
curr = next # set curr forward
return prev
def find_mid(self, head):
fast, slow = head, head
while (fast is not None) and (fast.next is not None):
slow = slow.next
fast = fast.next.next
return slow
head = Node(1)
head.next = Node(2)
head.next.next = Node(2)
head.next.next.next = Node(1)
# head.next.next.next.next = Node(2)
sol = Solution()
print(sol.isPalindrome(head))