您的位置:首页 > 其它

Palindrome Linked List 解答

2015-11-03 07:49 176 查看

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还是有难度。关键在于对以上每个子问题都熟悉。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
slow = head
quick = head
while quick.next is not None:
quick = quick.next
if quick.next is not None:
quick = quick.next
slow = slow.next
# Reverse sub list between slow.next and quick
cur = slow.next
slow.next = None
then = cur.next
cur.next = None
while then is not None:
tmp = then.next
then.next = cur
cur = then
then = tmp
second_head = cur
# Compare first sub list and second sub list
cur1 = head
cur2 = second_head
while cur1 is not None and cur2 is not None:
if cur1.val != cur2.val:
return False
cur1 = cur1.next
cur2 = cur2.next
return True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: