我在 Geeks for Geeks的 Linked List 挑战中做 Remove loop :
给定一个包含 N 个节点的链表,它可能包含一个循环。
这里的循环表示链表的最后一个节点连接到位置X的节点。如果链表没有任何循环,则X=0。
如果存在,则从链表中删除循环。
我试过这段代码:
class Solution:
def removeLoop(self, q):
slow,prev = q,None
fast = q
while slow and fast and fast.next:
prev = fast
slow = slow.next
fast = fast.next.next
if fast == slow:
print(prev.data)
prev.next = None
return
但它并非在所有情况下都能正常工作。
例如,当这是输入列表时,它会删除错误的链接:
1 → 2 → 3
↑ ↓
└── 4
在这种情况下,它会删除从 2 到 3 的链接,而应该删除从 4 到 2 的链接。
这是重现问题的代码:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def removeLoop(self, q):
slow,prev = q,None
fast = q
while slow and fast and fast.next:
prev = fast
slow = slow.next
fast = fast.next.next
if fast == slow:
print(prev.data) # Outputs 2, but should output 4
prev.next = None
return
# Create list 1 -> 2 -> 3 -> 4
one = Node(1)
two = Node(2)
three = Node(3)
four = Node(4)
one.next = two
two.next = three
three.next = four
# Add a link from last node to second node
four.next = two # cycle
Solution().removeLoop(one)
我不知道我哪里出错了?