Leetcode 234. Palindrome Linked List

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

Link: https://leetcode.com/problems/palindrome-linked-list/

Examples:

Example 1:
Input: 1->2
Output: false

Example 2:
Input: 1->2->2->1
Output: true

Example 3:
Input: 0->0
Output: true

思路: 回文检测,注意保存node.val

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head: return True
        p = head
        nodes = []
        while p:
            nodes.append(p.val)
            p = p.next
        n = len(nodes)
        if n % 2 == 0:
            half = int(n/2)
        else:
            half = int(n/2)+1
        i = 0
        while i < half:
            if nodes[i] != nodes[n-i-1]:
                break
            i += 1
        if i < half:
            return False
        return True

日期: 2020-12-01

posted @ 2020-12-01 16:00  summer_mimi  阅读(59)  评论(0编辑  收藏  举报