题目:
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(1)space需要in-place的reverse后半拉list,然后比较,用两个指针找到后半拉的起始位置。
C++版:
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL)
return true;
ListNode* s = head, *f = head;
while(f->next != NULL && f->next->next != NULL) {
f = f->next->next;
s = s->next;
}
s->next = reverse(s->next);
s = s->next;
ListNode* p = head;
while(s != NULL) {
if(s->val != p->val)
return false;
s = s->next;
p = p->next;
}
return true;
}
ListNode* reverse(ListNode* root) {
if(root->next == NULL)
return root;
ListNode* newRoot = reverse(root->next);
root->next->next = root;
root->next = NULL;
return newRoot;
}
};
Java版:
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null)
return true;
ListNode s = head, f = head;
while(f.next != null && f.next.next != null) {
s = s.next;
f = f.next.next;
}
s.next = reverse(s.next);
s = s.next;
ListNode p = head;
while(s != null) {
if(s.val != p.val)
return false;
s = s.next;
p = p.next;
}
return true;
}
public ListNode reverse(ListNode root) {
if(root.next == null)
return root;
ListNode newRoot = reverse(root.next);
root.next.next = root;
root.next = null;
return newRoot;
}
}
Python版:
class Solution:
# @param {ListNode} head
# @return {boolean}
def isPalindrome(self, head):
if head == None or head.next == None:
return True
fast, slow = head, head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
slow.next = self.reverse(slow.next)
slow = slow.next
p = head
while slow != None:
if slow.val != p.val:
return False
slow = slow.next
p = p.next
return True
def reverse(self, head):
if head.next == None:
return head
newHead = self.reverse(head.next)
head.next.next = head
head.next = None
return newHead