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?
一刷
题解:如果不修改input(即reverse它的下一半的话)是不可能达到O(n) time and O(1) space complexity的。
public boolean isPalindrome(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) { // odd nodes: let right half smaller
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while (slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
二刷
同上
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
//reverse the half
//find the medium
ListNode fast = head, slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//len is odd, from slow.next
if(fast != null){//odd
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while(slow != null){
if(slow.val!=fast.val) return false;
slow = slow.next;
fast = fast.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode prev = null;
while(head!=null){
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}