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?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//find mid point
if(head == null )
return true;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy,fast = dummy;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//now slow is on mid point;
//reverse second half
reverse(slow);
//compare first half to second half
ListNode runner1 = dummy.next;
ListNode runner2 = slow.next;
while(runner2 != null){
if(runner2.val != runner1.val){
return false;
}
runner2 = runner2.next;
runner1 = runner1.next;
}
return true;
// dummy -> 1 -> 2 -> 3 -> 4 -> 5 -> 4 -> 3 -> 2 -> 1
}
public void reverse(ListNode head){
//this head is the one node before the list need to reverse
if(head == null || head.next == null) return;
ListNode cur = head.next;
ListNode pre = null, next = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
head.next = pre;
}
}
Last updated