Leetcode 234. Palindrome Linked List

Posted wangyuxia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于Leetcode 234. Palindrome Linked List的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 234. Palindrome Linked List

Java [Leetcode 234]Palindrome Linked List

LeetCode 234. Palindrome Linked List

leetcode 234. Palindrome Linked List

LeetCode 234 Palindrome Linked List

LeetCode234. Palindrome Linked List