Palindrome Linked List Easy 0 attempts
LeetCode ↗

Palindrome Linked List

Easy Linked List LeetCode

Given the head of a singly linked list, check whether the sequence of values it holds reads the same forwards and backwards.

Input Format
Implement isPalindrome(head). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

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

Example 2

Input
head = [1,2]
Output
false
Constraints
  • 1 to 10^5 nodes
  • 0 <= Node.val <= 9
Test Cases (2)
Case 1
Args: [[1,2,2,1]] Expected: true
Case 2
Args: [[1,2]] Expected: false
Topics

Reverse Second Half

javascript
function isPalindrome(head) {
  let slow = head, fast = head;
  while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
  let prev = null;
  while (slow) { const next = slow.next; slow.next = prev; prev = slow; slow = next; }
  while (prev) {
    if (prev.val !== head.val) return false;
    prev = prev.next; head = head.next;
  }
  return true;
}

Time: O(n) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript