Created
May 16, 2022 12:20
-
-
Save mdpabel/726384720d19ff4e5b64c8c02823d9aa to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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 | |
This file contains hidden or 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 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