我的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]
,但我相信交换操作没有像我预期的那样执行,而且我很难理解为什么。
答案 0 :(得分:1)
如果您只有一个列表,并希望交替替换元素, 那么实现这一目标的最简单方法是使用 list slicing :
>>> 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]
答案 1 :(得分:0)
应该不是
current.next, current.next.next = current.next.next, current.next
是
current.next, current.next.next = current.next.next, current