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]

相关推荐
To_OC3 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎4 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC4 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
大模型码小白5 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧6 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
C^h10 小时前
python函数学习
人工智能·python·机器学习
Fanta丶10 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬10 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent
兜客互动10 小时前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_5386019710 小时前
智能体测开Day30pytest测试框架
python