【发布时间】:2021-12-06 08:11:09
【问题描述】:
我是一名初学者,自学成才的程序员,我正在学习数据结构课程。在运行 append 和 insert 方法后尝试调用 get_position 方法时遇到了障碍,我不明白为什么会发生这种情况。参考下面的代码,print(ll.get_position(5).value) 在调用 insert 方法之前打印“5”,在插入之后,我希望print(ll.get_position(6).value) 会打印“5”,但它会打印“3”。此外,我可以在 get_position 方法中将任何数字作为参数传递,即使数字超出链表的范围,它仍会打印“3”或“4”。我假设插入方法的while循环被卡住了?如何将e5 重新附加到链接列表?为什么会丢失?
谢谢!
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def get_position(self, position):
counter = 1
current = self.head
while current and counter <= position:
if counter == position:
return current
current = current.next
counter += 1
def insert(self, new_element, position):
counter = 1
current = self.head
if position < 1:
return None
elif position == 1:
new_element.next = self.head
self.head = new_element
while current and counter < position:
if counter == position - 1:
new_element.next = current.next
current.next = new_element
return
current = current.next
counter += 1
# Elements in list
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
e5 = Element(5)
# Linked List Setup
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
ll.append(e4)
ll.append(e5)
# Should print 5
print(ll.get_position(5).value)
ll.insert(e4, 3)
# Expected Ouput: 1,2,4,3,4
print(ll.get_position(1).value)
print(ll.get_position(2).value)
print(ll.get_position(3).value)
print(ll.get_position(4).value)
print(ll.get_position(5).value)
# Expected output: 5 (Actual Output 3)
print(ll.get_position(6).value)
# Expected output: Error. (Actual Output 4)
print(ll.get_position(7).value)
【问题讨论】:
-
你尝试插入一个已经在列表中的元素,因此它的“下一个”被覆盖了。
-
@MichaelButscher 谢谢!那么引用现有节点会在该节点和下一个节点之间创建一个循环链接?
-
是的,就是这样。
标签: python linked-list