Leetcode: 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?

Show Tags
Show Similar Problems

Solution

# 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

  1. if head==None or head.next==None: return head should return True
  2. for segmentate list, should add slow=slow.next for the case len(list)==2

你可能感兴趣的:(Leetcode: Palindrome Linked List)