Skip to content

Instantly share code, notes, and snippets.

@rungxanh1995
Created May 12, 2022 20:43
Show Gist options
  • Save rungxanh1995/d33db5dc5b2a72f7616d5d0b871b1778 to your computer and use it in GitHub Desktop.
Save rungxanh1995/d33db5dc5b2a72f7616d5d0b871b1778 to your computer and use it in GitHub Desktop.
Judge if a singly linked list is a palindrome (reversed is similar to the original one)

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:

Input: head = [1,2,2,1]
Output: true

Example 2:

Input: head = [1,2]
Output: false

Constraints:

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
# O(n) space, O(n) time complexity
compare_list = []
while head:
compare_list.append(head.val)
head = head.next
return compare_list[::] == compare_list[::-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment