无法在Python中交换LinkedList节点引用
我的LinkedList和节点类实现已从中被盗 我想交换LinkedList中的每两个节点,例如:无法在Python中交换LinkedList节点引用,python,pass-by-reference,swap,Python,Pass By Reference,Swap,我的LinkedList和节点类实现已从中被盗 我想交换LinkedList中的每两个节点,例如: Input: 0 1 2 3 4 5 6 7 8 9 Output: 1 0 3 2 5 4 7 6 9 8 我要创建的代码,然后尝试交换列表中的每两个元素,如下所示: for i in range(10): if i is 0: linkedlist = Linked_List() linkedlist.insert(str(i)) else:
Input: 0 1 2 3 4 5 6 7 8 9
Output: 1 0 3 2 5 4 7 6 9 8
我要创建的代码,然后尝试交换列表中的每两个元素,如下所示:
for i in range(10):
if i is 0:
linkedlist = Linked_List()
linkedlist.insert(str(i))
else:
linkedlist.insert(str(i))
current = linkedlist.first
while current is not linkedlist.last:
print(str(current))
print("NEXT =" + str(current.next))
print("NEXT.NEXT=" + str(current.next.next))
if current is linkedlist.first:
linkedlist.first = current.next
current.next, current.next.next = current.next.next, current.next
print(str(current))
print("NEXT =" + str(current.next))
print("NEXT.NEXT=" + str(current.next.next))
current = current.next
我的问题的核心是:
current.next, current.next.next = current.next.next, current.next
在我看来,这应该交换当前节点的引用和下一个节点的引用。导致第一种情况:
Node[0].next=Node[2]
Node[1].next=Node[0]
从而将列表从/更改为:
0 1 2 3 4 5 6 7 8 9
1 0 2 3 4 5 6 7 8 9
它似乎几乎可以工作,因为这个while
循环的第一次迭代的输出是:
Node[0]
NEXT =Node[1]
NEXT.NEXT=Node[2]
Node[0]
NEXT =Node[2]
NEXT.NEXT=Node[1]
它看起来与预期一样,但最后一行除外<代码>节点[0]。下一步=节点[2]是我下一步要看到的内容。我不明白为什么节点[2]。下一步=节点[1],但我相信交换操作没有像我预期的那样执行,我很难理解原因。如果您只是一个列表,并且希望交替交换元素, 实现这一点的最简单方法是使用列表切片: 不应该
current.next, current.next.next = current.next.next, current.next
是
欢迎来到StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。我们需要你的帖子中的所有示例,而不是外部来源的引用。谢谢,我已经添加了节点和链接列表实现啊,我现在知道你是正确的。我最初的代码只是导致了一个无休止的循环,因为第二个和第三个节点最终只是指向对方。非常感谢。仔细想想,仍然有一些bug。这是第一个循环的输出,包括您的更改:
Node[0]NEXT=Node[1]NEXT.NEXT=Node[2]Node[0]NEXT=Node[2]NEXT.NEXT=Node[0]
现在,如果current.NEXT==Node[2]
,那么current.NEXT.NEXT==Node[0]
怎么样?我相信我们没有改变节点[2]的引用。。。抱歉格式化。
>>> my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# v slice from `0`th index with step of `2`
# v v slice from `1`st index with step of `2`
>>> my_list[::2], my_list[1::2] = my_list[1::2], my_list[::2]
>>> my_list
[1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
current.next, current.next.next = current.next.next, current.next
current.next, current.next.next = current.next.next, current