Skip to content

Instantly share code, notes, and snippets.

@mdpabel
Created May 16, 2022 12:20
Show Gist options
  • Select an option

  • Save mdpabel/726384720d19ff4e5b64c8c02823d9aa to your computer and use it in GitHub Desktop.

Select an option

Save mdpabel/726384720d19ff4e5b64c8c02823d9aa to your computer and use it in GitHub Desktop.
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
"""
1 2 3 4 5
1 2
2 4
3 None
"""
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
print(slow.val)
"""
Head->1->2->3->4->5->None
p = 5
c = N
n = N
5->4->3->None
"""
prev_node = None
curr_node = slow
while curr_node:
next_node = curr_node.next
curr_node.next = prev_node
prev_node, curr_node = curr_node, next_node
left = head
right = prev_node
while left and right:
if left.val != right.val:
return False
left = left.next
right = right.next
return True
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
stack = []
node = head
while node:
stack.append(node.val)
node = node.next
left = 0
right = len(stack) - 1
while left < right:
if stack[left] != stack[right]:
return False
left += 1
right -= 1
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment