234 Palindrome Linked List
这道题如果不要求space O(1) 代码写起来就相当简单。 但是要求 O(1),唯一的方法就是reverse 前半部分linked List 在做比较, 稍微注意长度为奇偶时一点小小的区别。写起来还是很费劲的
class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): dummy = ListNode(0) dummy.next = head p1, p2, length = dummy, dummy,0 while p2.next != None: p1 = p1.next p2 = p2.next length += 1 if p2.next == None: break p2 = p2.next length += 1 p2 = p1.next p1 = self.reverse(head, p1) if length % 2 == 1: p1 = p1.next while p2 != None: if p1.val != p2.val: return False p1, p2 = p1.next, p2.next return True def reverse(self, head, p1): if head == p1: return head if head == None: return net = head.next head.next = None rest = self.reverse(net,p1) net.next = head return rest