Palindrome Linked List(lintcode 223)
Description
Implement a function to check if a linked list is a palindrome.
Example
Given 1->2->1, return true.
Interface
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
public boolean isPalindrome(ListNode head) {
// Write your code here
}
}
Idea
The code destroy the original structure of the list. If you don't want to do that, reverse the second part back.
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
public boolean isPalindrome(ListNode head) {
// Write your code here
if (head == null) {
return true;
}
ListNode mid = findMid(head);
ListNode newHead = reverse(mid);
while (newHead != null) {
if (newHead.val != head.val) {
return false;
}
newHead = newHead.next;
head = head.next;
}
return true;
}
private ListNode findMid(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
private ListNode reverse(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode nxt = head.next;
head.next = newHead;
newHead = head;
head = nxt;
}
return newHead;
}
}