Skip to content

Instantly share code, notes, and snippets.

@HauptJ
Created March 14, 2020 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HauptJ/aa81db18f522fba2225ea84fed617849 to your computer and use it in GitHub Desktop.
Save HauptJ/aa81db18f522fba2225ea84fed617849 to your computer and use it in GitHub Desktop.
LinkedList Palindrome - Stack
# 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
@HauptJ
Copy link
Author

HauptJ commented Mar 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment