leetcode 234.回文链表

暴力解法:

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:

        if head.next==None:
            return True

        list1 = []
        A = head
        while(A!=None):
            list1.append(A.val)
            A = A.next
        
        
        tou = 0
        wei = len(list1)-1
        if len(list1)%2==0:
            while(tou!=(wei-1)):
                if (list1[tou] != list1[wei]):
                    return False
                tou += 1
                wei -= 1
            if (list1[tou]==list1[wei]):
                return True
            else:
                return False    
        else:
            while(tou!=(wei-2)):
                if (list1[tou] != list1[wei]):
                    return False
                tou += 1
                wei -= 1
            if (list1[tou]==list1[wei]):
                return True
            else:
                return False   

官方代码(完全没想到 vals == vals[::-1]):

python 复制代码
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        vals = []
        current_node = head
        while current_node is not None:
            vals.append(current_node.val)
            current_node = current_node.next
        return vals == vals[::-1]

作者:力扣官方题解
链接:https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

切片:[start:stop:step]

相关推荐
2301_7751481512 小时前
如何授权AWR报告生成_GRANT SELECT ANY DICTIONARY诊断权限
jvm·数据库·python
圣保罗的大教堂13 小时前
leetcode 3761. 镜像对之间最小绝对距离 中等
leetcode
刀法如飞13 小时前
一款Python语言Django框架DDD脚手架,开箱即用
python·架构·django
6Hzlia13 小时前
【Hot 100 刷题计划】 LeetCode 108. 将有序数组转换为二叉搜索树 | C++ 分治法详解
c++·算法·leetcode
itzixiao14 小时前
L1-051 打折(5分)[java][python]
java·python·算法
HappyAcmen14 小时前
10.常见报错排查与基础调试
开发语言·python
山川而川-R14 小时前
Windows新系统_安装anaconda-2026-4.24
python
ID_1800790547314 小时前
Python 实现京东商品详情 API 数据准确性校验(极简可直接用)
java·前端·python
码农的神经元14 小时前
配电网智能决策平台:从风险感知到自愈控制的 Python 实现
开发语言·python
zhaoshuzhaoshu14 小时前
主流 AI 编程助手工具特点与对比
人工智能·python