LeetCode-234. Palindrome Linked List

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?

判断一个链表是不是回文的。

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 not head or not head.next:
            return True
        # find the mid node
        fast = slow = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        # reverse the second part
        node = None
        while slow:
            slow.next, slow, node = node, slow.next, slow
        # compare the first and second part
        while node:
            if node.val != head.val:
                return False
            node = node.next
            head = head.next
        return True
posted @ 2017-01-03 12:00  BinWone  阅读(113)  评论(0编辑  收藏  举报