234. Palindrome Linked List

Problem

Given a singly linked list, determine if it is a palindrome.

判断一个链表是不是回文结构

solution

转换为python列表,利用切片

vals += head.val, #附加tuple有效率提升

def isPalindrome(self, head):
    vals = []
    while head:
        vals += head.val,
        head = head.next
    return vals == vals[::-1]

discuss 时间复杂度更快的方法

def isPalindrome(self, head):
    fast = slow = head
    # find the mid node
    while fast and fast.next:
        fast = fast.next.next
        slow = slow.next
    # reverse the second half
    node = None
    while slow:
        nxt = slow.next
        slow.next = node
        node = slow
        slow = nxt
    # compare the first and second half nodes
    while node: # while node and head:
        if node.val != head.val:
            return False
        node = node.next
        head = head.next
    return True
posted @ 2016-09-27 21:15  Salmd  阅读(72)  评论(0)    收藏  举报