Leetcode回文链表

Leetcode回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

示例 1:

输入:head = [1,2,2,1]
输出:true

示例 2:

输入:head = [1,2]
输出:false

提示:

  • 链表中节点数目在范围[1, 105] 内

  • 0 <= Node.val <= 9

作者:力扣 (LeetCode)
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnv1oc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

栈 先进后出

看到回文子串第一反应就是栈。首先将所有元素进栈。然后再依次出栈和原来的链表节点对比,相同则为True,不同则为False。

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        """栈"""
        stack = list()  # 创建一个栈
        h = head
        while h:
            stack.append(h) # 链表元素全部进栈
            h = h.next
        n1 = head 
        while stack:
            n2 = stack.pop()  # 出栈
            if n1.val != n2.val:
                return False
            n1 = n1.next
        return True

在这里插入图片描述

可以看到用时很长。

猜你喜欢

转载自blog.csdn.net/qq_43418888/article/details/125753511
今日推荐