编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
# 使用list存储value
stack = []
while head:
stack.append(head.val)
head = head.next
if len(stack) <= 1:
return True
reverse = stack[::-1]
if stack == reverse:
return True
else:
return False
本文介绍了一种检查链表是否为回文的算法实现,通过将链表元素存储到数组中并比较其正反顺序的一致性来判断。示例代码展示了如何使用Python进行实现。
875

被折叠的 条评论
为什么被折叠?



