class LinkNode: def __init__(self, data): self.val = data self.next = None class Solution(object): def isPalindrome(self, head): if not head or not head.next: # 链表为空或是只有一个元素 return True slow = head fast = head.next # 创建快慢指针,寻找链表中点 while fast and fast.next: # 快指针到达结尾为止 fast = fast.next.next if fast: # 当前快指针fast的位置为奇数位置, slow = slow.next # 慢指针保持指向左侧最后一个元素 # second要指向右侧第一个元素(偶)或是中间的右侧第一个元素(奇) if fast: # 链表有奇数个元素 second = slow.next else: second = slow.next.next slow.next = None first = head pre = None while first: # 翻转左侧链表 tmp = first.next first.next = pre pre = first first = tmp first = pre while first and second: if first.val != second.val: return False first = first.next second = second.next return True p1 = LinkNode(1) p2 = LinkNode(2) p3 = LinkNode(3) p4 = LinkNode(2) p5 = LinkNode(1) p1.next = p2 p2.next = p3 p3.next = p4 p4.next = p5 print(Solution().isPalindrome(p1))
回文链表:判定一个链表内容是否是回文结构,快慢指针法
最新推荐文章于 2025-04-21 21:00:00 发布