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]

相关推荐
m0_747124532 小时前
LangChain RAG Chain Types 详解
python·ai·langchain
平安的平安2 小时前
Python + AI Agent 智能体:从原理到实战,构建自主决策的 AI 助手
开发语言·人工智能·python
Mr_Xuhhh2 小时前
深入理解Java数组:从定义到高阶应用
开发语言·python·算法
倦王2 小时前
力扣日刷复习:
算法·leetcode·职场和发展
小陈工2 小时前
Python Web开发入门(九):权限管理与角色控制实战
服务器·开发语言·前端·数据库·python·安全·sqlite
Etherious_Young2 小时前
关于储油罐的变位识别与罐容表的标定的Python方案
python·数学建模
孙华贵2 小时前
python编程怎么赚钱
开发语言·python
tryCbest2 小时前
Python之Falsk开发框架(第四篇)- Flask 知识总结与完整博客系统实战
开发语言·python·flask
观测云2 小时前
Python 应用实现 APM 自动注入(Kubernetes 篇)
开发语言·python·kubernetes