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]

相关推荐
2603_965148118 分钟前
eBay商品数据API:寻找海外仓与价格洼地
大数据·人工智能·windows·python·microsoft
2601_9563198816 分钟前
TqSdk Tick 数据适合做什么?获取方法与使用边界
人工智能·python
苏灿烤鱼1 小时前
把 Agent 做成一家公司,真比通用提示词好用吗?
python·agent·shell
Doraemomo9 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore10 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
北斗落凡尘10 小时前
LangGraph 入门实战(2)
python·langchain
ttod_qzstudio11 小时前
Java 常用语法极简通关(五):类与对象——字段、方法、构造器、this 与 static
java·开发语言·python
jufeng130712 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 1 篇】
人工智能·python·架构·agent
月光船幽幽13 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法