Skip to content

234. Palindrome Linked List

Linked List Two Pointers Stack Recursion

Problem - Palindrome Linked List

Easy

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

 

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

 

Follow up: Could you do it in O(n) time and O(1) space?

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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:
        # slow, fast = head, head.next
        # while fast and fast.next:
        #     slow, fast = slow.next, fast.next.next
        # last, current = None, slow.next

        # while current:
        #     tmp = current.next
        #     current.next = last
        #     last, current = current, tmp

        # while last:
        #     if last.val != head.val:
        #         return False
        #     last, head = last.next, head.next

        # return True

        dummy = head
        nums = []
        while dummy:
            nums.append(dummy.val)
            dummy = dummy.next
        return nums == nums[::-1]

Submission Stats:

  • Runtime: 15 ms (95.28%)
  • Memory: 39.2 MB (49.46%)