【发布时间】:2018-07-17 01:54:29
【问题描述】:
我的 LinkedList 和 Node 类实现已从 here 窃取。
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
return 'Node[' + self.value +']'
class Linked_List:
def __init__(self):
self.first = None
self.last = None
def insert(self, x):
if self.first is None:
self.first = Node(x, None)
self.last = self.first
elif self.last is self.first:
self.last = Node(x,None)
self.first.next = self.last
else:
current = Node(x, None)
self.last.next = current
self.last = current
def __str__(self):
if self.first is not None:
current = self.first
out = 'LinkedList[\n' + str(current.value) + '\n'
while current.next is not None:
current = current.next
out += str(current.value) + '\n'
return out + ']'
def clear(self):
self.__init__()
我想交换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:
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]
看起来和预期的一样,除了是最后一行。 Node[0].next=Node[2] 是我接下来要看到的。我不明白为什么Node[2].next=Node[1],但我相信交换操作没有像我预期的那样执行,我很难理解为什么。
【问题讨论】:
-
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。我们需要您发布的所有示例,而不是对外部资源的引用。
-
谢谢,我已经添加了Node和Linked_List实现
标签: python pass-by-reference swap