LeetCode 0234. Palindrome Linked List Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0234. Palindrome Linked List

Description

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

Solution 1: Fast and Slow Pointers

We can use fast and slow pointers to find the middle of the linked list, then reverse the right half of the list. After that, we traverse both halves simultaneously, checking if the corresponding node values are equal. If any pair of values is unequal, it's not a palindrome linked list; otherwise, it is a palindrome linked list.

The time complexity is O(n), where n is the length of the linked list. The space complexity is O(1).

PythonJavaC++GoTypeScriptJavaScriptC#
# 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 pre, cur = None, slow.next while cur: t = cur.next cur.next = pre pre, cur = cur, t while pre: if pre.val != head.val: return False pre, head = pre.next, head.next return True(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !