题目
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
O(n) time, O(n) space
class Solution {
public boolean isPalindrome(ListNode head) { return recur(head, head) == null;}
public ListNode recur(ListNode curr, ListNode head) {
if(curr == null) return head;
ListNode ret = recur(curr.next, head);
return (ret.val == curr.val)? ret.next : ret;
}
}
O(n) time, O(1) space
class Solution {
public ListNode reverseList(ListNode head) {
ListNode next;
ListNode curr = head;
ListNode newlist = null;
while(curr != null) {
next = curr.next;
curr.next = newlist;
newlist = curr;
curr = next;
}
return newlist;
}
public boolean isPalindrome(ListNode head) {
// Find middle node
int size = 0, count = 0;
ListNode curr = head, middle_node = null, curr2 = null;
while(curr != null) {
size++;
curr = curr.next;
}
int middle = (size % 2 == 0) ? size / 2 : size / 2 + 1;
curr = head;
while(curr != null) {
if(count == middle) {
middle_node = curr;
}
curr = curr.next;
count++;
}
// Reverse list starting from the middle...
ListNode reversed = reverseList(middle_node);
// You want reversed == head for the first size / 2 elements
curr = head;
curr2 = reversed;
count = 0;
while(count < size / 2) {
if(curr.val != curr2.val) return false;
curr = curr.next;
curr2 = curr2.next;
count++;
}
return true;
}
}