
class Node:
def __init__(self, x):
self.value = x
self.next = None
class LinkedListMid:
def __init__(self):
self.size = 0
self.head = Node(0)
def midOrUpMidNode(self, head):
if head is None or head.next is None or head.next.next is None:
return head
# 链表有三个点或以上
slow = head.next
fast = head.next.next
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def midOrDownMidNode(self, head):
if head is None or head.next is None:
return head
slow = head.next
fast = head.next
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def midOrUpMidPreNode(self, head):
if head is None or head.next is None or head.next.next is None:
return None
slow = head
fast = head.next.next
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def midOrDownMidPreNode(self, head):
if head is None or head.next is None:
return None
if head.next.next is None:
return head
slow = head
fast = head.next
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow









本文介绍了如何在链表中使用四种不同的方法找到中位节点:midOrUpMidNode、midOrDownMidNode、midOrUpMidPreNode和midOrDownMidPreNode,适用于链表包含至少三个节点的情况。算法详细展示了如何通过快慢指针技巧确定链表的中间位置,包括中位节点和可能的前驱节点。
1235

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



