-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode 234 - palindrome linked list.py
58 lines (45 loc) · 1.61 KB
/
leetcode 234 - palindrome linked list.py
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
# palindrome linked list | leetcode 234 | https://leetcode.com/problems/palindrome-linked-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# to check if its palindrome
def isPalindrome(self, head) -> bool:
# if underflow, is palindrome
if not head or not head.next: return True
# get one before mid element
# and check if number of elements are even
mid, even = self.get_mid(head)
second = mid.next
if not even: second = second.next
# reverse the first half of the linked list
first = self.rev_ll(head, mid)
# match the reversed 1st and normal 2nd halves
while first and second:
if first.val != second.val: return False
first = first.next
second = second.next
return True
# to reverse the linked list half
def rev_ll(self, head, upto):
prev, curr = None, head
while curr and prev != upto:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
# to get the mid element
# and check for even
def get_mid(self, head):
prev = head
slow = head
fast = head.next
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
if not fast: return prev, False
return slow, True