Created
March 14, 2020 16:10
-
-
Save HauptJ/aa81db18f522fba2225ea84fed617849 to your computer and use it in GitHub Desktop.
LinkedList Palindrome - Stack
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
# Definition for singly-linked list. | |
# class ListNode: | |
# def __init__(self, x): | |
# self.val = x | |
# self.next = None | |
class Solution: | |
def isPalindrome(self, head: ListNode) -> bool: | |
# low hanging fruit | |
if not head: | |
return True | |
palindrome = True | |
stack = [] | |
tmpNode = ListNode() # tmpNode is going to be used to load the stack | |
tmpNode = head | |
# 1.) Traverse the list from head to tail and push every visited node to the stack | |
while tmpNode is not None: # None is Python's equivalent to null | |
stack.append(tmpNode.val) | |
tmpNode = tmpNode.next | |
''' | |
2.) Traverse the list again. For every visited node, pop a node from the stack and coompare the val of the popped node with the current node in the LL | |
If the current val of the node in the LL does not equal the val of node popped from the stack, return False. We clearly don't have a palindrome | |
If the val of the node in the LL equals the val of thge node popped from the stack, continue. We will finish when we reach the end of the LL or find a mismatch | |
''' | |
while head is not None: | |
stackVal = stack.pop() | |
if head.val != stackVal: | |
palindrome = False | |
break | |
else: | |
palindrome = True | |
head = head.next | |
return palindrome |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LeetCode 234. Palindrome Linked List
Video walk through - YouTube
Video walk through - Vimeo