【LEETCODE】234-Palindrome Linked List

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?


参考:

http://bookshadow.com/weblog/2015/07/10/leetcode-palindrome-linked-list/


快慢指针:

http://www.cnblogs.com/twobin/p/3361227.html


普通方法:先遍历一遍单链表确定其长度L后,再从头节点出发循环L/2次即可查找到单链表的中间节点。该问题如果采用普通的方法虽然简单,但是查找效率太低。

快慢指针:设置两个指针*fast、*slow都指向单链表的头节点,其中*fast的移动速度是*slow的2倍,当*fast指向末尾节点的时候,slow正好就在中间了,可以大大提高查找的效率。

当然,此时算法还要考虑链表结点个数的奇偶数因素,当快指针移动x次后到达表尾(1+2x),说明链表有奇数个结点,直接返回慢指针指向的数据即可。如果快指针是倒数第二个结点,说明链表结点个数是偶数,这时可以实际情况返回上中位数或下中位数或(上中位数+下中位数)的一半。




# 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=fast=head
        
        #快慢指针
        while fast.next and fast.next.next:
            slow=slow.next
            fast=fast.next.next
        
        #倒置后半部分
        p=slow.next           #不管奇偶 p都位于后半部分的头
        last=None
        while p:
            next=p.next
            p.next=last       #最后slow.next.next is None
            last=p            #last最后位于最后一个
            p=next
        
        #p1从前半部分的头 p2从后半部分的头 开始比较值是否相等
        p1=head
        p2=last
        while p2 and p1.val==p2.val:
            p1=p1.next
            p2=p2.next
        
        #恢复原结构,不恢复也可以AC
        p=last
        last=None
        while p:
            next=p.next
            p.next=last
            last=p
            p=next
        
        return p2 is None    #如果回文,最后p2是None,否则,p2是开始不相等的那个点



你可能感兴趣的:(LeetCode,python)