Palindrome Linked List 解答

Question

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?

Solution

这一题思路并不难。要满足follow-up的要求,我们用到了快慢指针。

1. 用快慢指针得到前后两半list,这里有个技巧是quick先判断有无next,slow再走。这样就保证slow永远指向后半部分的前一个结点

2. Reverse 后半部分的list。三指针方法

3. 比较前半链表和反转后的后半链表

思路虽不难,但是要做到bug-free还是有难度。关键在于对以上每个子问题都熟悉。

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def isPalindrome(self, head):
 9         """
10         :type head: ListNode
11         :rtype: bool
12         """
13         if head is None or head.next is None:
14             return True
15         slow = head
16         quick = head
17         while quick.next is not None:
18             quick = quick.next
19             if quick.next is not None:
20                 quick = quick.next
21                 slow = slow.next
22         # Reverse sub list between slow.next and quick
23         cur = slow.next
24         slow.next = None
25         then = cur.next
26         cur.next = None
27         while then is not None:
28             tmp = then.next
29             then.next = cur
30             cur = then
31             then = tmp
32         second_head = cur
33         # Compare first sub list and second sub list
34         cur1 = head
35         cur2 = second_head
36         while cur1 is not None and cur2 is not None:
37             if cur1.val != cur2.val:
38                 return False
39             cur1 = cur1.next
40             cur2 = cur2.next
41         return True

 

posted @ 2015-11-03 07:49  树獭君  阅读(214)  评论(0编辑  收藏  举报