-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0234-palindrome-linked-list.py
More file actions
79 lines (64 loc) · 1.91 KB
/
0234-palindrome-linked-list.py
File metadata and controls
79 lines (64 loc) · 1.91 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
79
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None:
return True
firstHalfEnd = self.endOfFirstHalf(head)
secondHalfStart = self.reverseList(firstHalfEnd.next)
result = True
firstPos = head
seconfPos = secondHalfStart
while result and seconfPos:
if firstPos.val != seconfPos.val:
result = False
firstPos = firstPos.next
seconfPos = seconfPos.next
firstHalfEnd.next = self.reverseList(secondHalfStart)
return result
def endOfFirstHalf(self, head: ListNode) -> ListNode:
fast = head
slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return slow
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
nextNode = curr.next
curr.next = prev
prev = curr
curr = nextNode
return prev
# time complexity: O(n)
# space complexity: O(n)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
palindromList = []
while head:
palindromList.append(head.val)
head = head.next
i = 0
j = len(palindromList) - 1
while i < j:
if palindromList[i] != palindromList[j]:
return False
i += 1
j -= 1
return True
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(2)
root.next.next.next = ListNode(1)
print(Solution().isPalindrome(root))