菜鸟扣代码第七天:leetcode234--回文链表

题目描述:

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true

代码:

class Solution:
    def isPalindrome(self, head):
       
        if head is None or head.next is None:
            return True
        l = []
        p = head
        while p.next:
            l.append(p.val)
            p = p.next
        l.append(p.val)
        return l == l[::-1]

测试:

输入
[1,2]
输出
false
预期结果
false

输入
[1,2,3,2,1]
输出
true
预期结果
true

猜你喜欢

转载自blog.csdn.net/weixin_51239526/article/details/109250498