Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

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

Solution

Using stack.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        // read all items with two pointers (slow, fast * 2, when fast.next is null, slow is in the middle), put all middle into stack and then continue reading the slow and all values must match values from stack, if not, return false
        if (head == null || head.next == null) return true;
        ListNode slow = head;
        ListNode fast = head;
        Stack<ListNode> stack = new Stack<>();
        while (fast != null && fast.next != null) {
            stack.add(slow);
            slow = slow.next;
            fast = fast.next.next;
        }

        if (fast != null) { // if fast is not null, the number of elements is odd, 
        // and we want to move slow by one, e.g. 1 -> 0 -> 1
            slow = slow.next;
        }

        while (slow != null) {
            if (stack.isEmpty()) return false;
            ListNode fromStack = stack.pop();
            if (slow.val != fromStack.val) {
                return false;
            }
            slow = slow.next;
        }
        return true;
    }
}

Other solutions.

Space optimized.

Last updated

Was this helpful?