class ListNode:
def __init__(self, item):
self.val = item
self.next = None
class LinkedList:
def rear_insert(self, li):
if not li:
return None
head = ListNode(li[0])
tail = head
for val in li[1:]:
node = ListNode(val)
tail.next = node
tail = node
return head
def print(self, head):
current = head
while current:
print(current.val, end="->")
current = current.next
print(None)
li = [1, 2, 1]
l = LinkedList()
res = l.rear_insert(li)
# 通过栈的pop函数解题
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
stack = []
tmp = head
while tmp:
stack.append(tmp.val)
tmp = tmp.next
while head:
if head.val != stack.pop():
return False
head = head.next
return True
l.print(res)
ll = Solution()
print(ll.isPalindrome(res))
LCR 027. 回文链表
Python链表操作与回文判断:类定义与方法应用
最新推荐文章于 2025-11-29 16:24:14 发布
本文介绍了如何使用Python创建链表类(LinkedList),实现后部插入(rear_insert)和打印(print)功能。同时,通过Solution类中的isPalindrome方法,利用栈来判断链表是否是回文,展示了链表操作在解决回文问题中的应用。
597

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



