meta data for this page
  •  

Palindrome Linked List

Leetcode


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

Example 1:

assets.leetcode.com_uploads_2021_03_03_pal1linked-list.jpg

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

Solution 1

Solution 1

class Solution {
  private ListNode head;
  public boolean isPalindrome(ListNode head) {
    this.head = head;
    return compare(head);
  }
 
  private boolean compare(ListNode tail) {
    if (tail == null) return true;
    boolean matched = compare(tail.next) && head.val == tail.val;
    head = head.next;
    return matched;
  }
}