Problem
Implement a function to check if a linked list is a palindrome.
Example
Given 1->2->1, return true.
Key
create new list nodes:
ListNode pre = null;
//null, 1-2-3-4
//1-null, 2-3-4
//2-1-null, 3-4
//3-2-1-null, 4
//4-3-2-1-null, null
while (head != null) {
ListNode cur = new ListNode(head.val);
cur.next = pre;
pre = cur;
head = head.next;
}
Solution
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null) return true;
ListNode reversed = reverse(head);
while (head != null) {
if (head.val != reversed.val) return false;
head = head.next;
reversed = reversed.next;
}
return true;
}
private ListNode reverse(ListNode head) {
ListNode pre = null;
//null, 1-2-3-4
//1-null, 2-3-4
//2-1-null, 3-4
//3-2-1-null, 4
//4-3-2-1-null, null
while (head != null) {
ListNode cur = new ListNode(head.val);
cur.next = pre;
pre = cur;
head = head.next;
}
return pre;
}
}