Palindrome Linked List
Check whether the values of a singly linked list read the same from both ends, without copying them.
Given the headtruefalse
Example 1
Output: true
Example 2
Output: false
Example 3
Output: true
The Idea
You have probably met words like "level" or "racecar", which give the same letters whether you read them from the left or from the right. Words like these are called palindromes, and a list of numbers can be one too. Read 1, 2, 2, 1 from either end and you get 1, 2, 2, 1, which is why Example 1 returns true
The numbers here sit in a singly linked list. Each value is kept in a node, and each node knows only the node after it, through its nextnextnullhead
With an array, we would put one finger on the first value and one on the last, and move them toward each other, comparing as we go. In the list, the right-hand finger is stuck: the last 1 has no link back to the 2 before it. So how can we read the list from the end?
We do not have to. Only the second half needs to be read backwards, and we can turn its links around. Then the last node becomes the start of a short list that runs back toward the middle, and both halves can be walked forwards, side by side. Look at the picture below.
The top row, labelled "1. slow and fast find the middle", shows how to find where the second half starts. Two markers start at headslowfastfastnullslow
The bottom row, labelled "2. after reversing the second half", shows the same nodes after the links from that 2 onwards are turned around. The last 1 now points back at the 2, and the 2 points to nullpqqnull
So the list never has to be read backwards. It is enough to turn half of it around, compare two forward walks, and turn that half back.
Solution Approach
The simple way with an array shows what the reversal saves; after it, the code has four things to settle: finding the middle, reversing the second half, knowing when the comparison stops, and giving the list back unchanged.
The simple way with an array
Why not copy the values into an array and compare from both ends there? That works, and it takes O(n) time. But the array holds a copy of every value, so the extra memory grows with the list. Reversing half of the list in place needs only a few variables, whatever its length.
Finding the middle
How do we know where the second half starts, without knowing the length? We could count the nodes first and then walk half that far. The slowfastfast
For an odd length such as Example 3, [1, 2, 3, 2, 1], slowslow
Reversing the second half
How do we turn the links around? Walk the second half one node at a time and point each node's nextnext
One link is left alone: the node just before slowslow
When the comparison stops
Which walk decides when to stop? The reversed half, because it is never longer than the walk from the head. The comparison runs while qnull
Giving the list back
Why put the list back? Whoever called the method only asked a question, and may still need the list afterwards. Reversing the reversed half again restores every link, and the node before the middle never lost its link, so the list is whole again. For this to run on a mismatch too, the answer is stored in a variable and the loop is left with break
Java Solution
The method isPalindrome
- First, find the middle.
andslow both start atfast . Whilehead andfast are notfast.next ,null moves one node andslow moves two.fast - Reverse the list from
onwards with the helperslow , and keep the start of the reversed half inreverse . Insidesecond ,reverse starts asprev . For each node, it saves the following node innull , points the node atnext , and moves both one step on.prev - Compare the halves.
starts atp ,head atq , andsecond starts assame . Whiletrue is notq , compare their values: on a difference, setnull tosame and break out, otherwise move both on.false - Call
again to put the links back, then returnreverse(second) .same
The mainListNodebuildshow
public class PalindromeLinkedList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static boolean isPalindrome(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) { // fast moves two nodes, slow one
slow = slow.next;
fast = fast.next.next;
}
ListNode second = reverse(slow); // reverse the second half
ListNode p = head;
ListNode q = second;
boolean same = true;
while (q != null) { // the reversed half decides when to stop
if (p.val != q.val) {
same = false;
break;
}
p = p.next;
q = q.next;
}
reverse(second); // put the list back as it was
return same;
}
private static ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev; // turn this link around
prev = head;
head = next;
}
return prev;
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode n = head; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? ", " : "");
}
return sb.append("]").toString();
}
static void check(int... values) {
ListNode head = build(values);
String before = show(head);
boolean result = isPalindrome(head);
System.out.println(before + " -> " + result + ", list afterwards: " + show(head));
}
public static void main(String[] args) {
check(1, 2, 2, 1);
check(1, 2);
check(1, 2, 3, 2, 1);
check(1, 2, 3, 1);
check(7);
check();
}
}
Running it prints:
[1, 2, 2, 1] -> true, list afterwards: [1, 2, 2, 1]
[1, 2] -> false, list afterwards: [1, 2]
[1, 2, 3, 2, 1] -> true, list afterwards: [1, 2, 3, 2, 1]
[1, 2, 3, 1] -> false, list afterwards: [1, 2, 3, 1]
[7] -> true, list afterwards: [7]
[] -> true, list afterwards: []
The answers truefalsetruesamefalsereverse
The last two lines are the smallest lists. For [7], slowqpheadnullreverse(null)nulltrue
The loop condition on qwhile (p != null)q.valqnullNullPointerException
Complexity
The method walks the list a fixed number of times and keeps only a handful of node references.
- Time: O(n).
andslow cross the list once, each of the two reversals touches only the nodes from the middle on, and the comparison takes at most that many steps.fast - Space: O(1). The second half is turned around by changing the
links of the existing nodes, so no copy of the values is made, only a few variables such asnext ,slow ,p andq .prev