码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 234. Palindrome Linked List

时间:2020-12-05 11:02:42      阅读:7      评论:0      收藏:0      [点我收藏+]

标签:inpu   node   ref   ==   return   false   注意   isp   com   

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

标签:inpu   node   ref   ==   return   false   注意   isp   com   

原文地址:https://www.cnblogs.com/wangyuxia/p/14068799.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!