Last active
January 31, 2022 18:20
-
-
Save mhsharifi96/7c09ab7689ec49742bf2450528b66815 to your computer and use it in GitHub Desktop.
Palindrome Linked List in Python with O(1) Extra Space (O(n) time)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ListNode: | |
def __init__(self, val=0, next = None): | |
self.next = next | |
self.val = val | |
class Solution: | |
def isPalindrome(self, head:ListNode) -> bool: | |
fast = head | |
slow = head | |
#find middle | |
while fast and fast.next : | |
fast = fast.next.next | |
slow = fast.next | |
# reverse second half | |
prev = None | |
while slow: | |
temp = slow.next | |
slow.next = prev | |
prev = slow | |
slow = temp | |
#check palindrome | |
left, right = head,prev | |
while right : | |
if left.val == right.val : | |
return False | |
left = left.next | |
right = right.next | |
return True | |
def make_list(elements): | |
head = ListNode(elements[0]) | |
for element in elements[1:]: | |
ptr = head | |
while ptr.next: | |
ptr = ptr.next | |
ptr.next = ListNode(element) | |
return head | |
head = make_list([1,2,3,2,1]) | |
ob1 = Solution() | |
print(ob1.isPalindrome(head)) # True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment