您的位置:首页 > 其它

Leetcode: Palindrome Linked List

2015-08-29 11:15 441 查看

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?

Show Tags

Show Similar Problems

Solution

[code]# 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==None or head.next==None:
            return True

        # segmentate list
        slow, fast = (head,)*2
        while fast.next!=None and fast.next.next!=None:
            slow = slow.next
            fast = fast.next.next
        slow = slow.next    

        head1,head2 = head,slow
        head2 = self.reverselist(head2)

        while head2!=None:
            if head1.val!=head2.val:
                return False

            head1, head2 = head1.next, head2.next

        return True

    def reverselist(self, head):
        if head==None or head.next==None:
            return head

        tail = head.next
        newhead = self.reverselist(tail)

        tail.next = head
        head.next = None

        return newhead


Error Path

if head==None or head.next==None: return head should return True

for segmentate list, should add slow=slow.next for the case len(list)==2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: