Python链表delete函数调试及insert方法修复方案
问题描述
我正在学习一门包含Python链表操作的在线课程,课程要求为LinkedList类实现get_position、insert和delete方法,并运行脚本底部的测试用例得到预期结果。我卡在delete函数上数日,未能找到问题所在。
原始代码
"""The LinkedList code from before is provided below. Add three functions to the LinkedList. "get_position" returns the element at a certain position. The "insert" function will add an element to a particular spot in the list. "delete" will delete the first element with that particular value. Then, use "Test Run" and "Submit" to run the test cases at the bottom.""" 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): """Get an element from a particular position. Assume the first position is "1". Return "None" if position is not in the list.""" current = self.head i = 1 if self.head: while i < position: current = current.next i = i + 1 return current else: return None def insert(self, new_element, position): """Insert a new node at the given position. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements.""" current = self.head i = 1 if self.head: while i < position - 1: current = current.next i = i + 1 current.next = new_element while current.next: current = current.next else: self.head = new_element pass def delete(self, value): """Delete the first node with a given value.""" if self.head is None: raise Exception("List is empty") if self.head.value == value: self.head = self.head.next current = self.head i = 1 while current.next: current = current.next return previous = self.head for element in self: if element.value == value: previous.next = element.next return previous = element # Test cases # Set up some Elements e1 = Element(1) e2 = Element(2) e3 = Element(3) e4 = Element(4) # Start setting up a LinkedList ll = LinkedList(e1) ll.append(e2) ll.append(e3) # Test get_position # Should print 3 print ll.head.next.next.value # Should also print 3 print ll.get_position(3).value # Test insert ll.insert(e4,3) # Should print 4 now print ll.get_position(3).value # Test delete ll.delete(1) # Should print 2 now print ll.get_position(1).value # Should print 4 now print ll.get_position(2).value # Should print 3 now print ll.get_position(3).value
报错信息
Traceback (most recent call last): File "vm_main.py", line 31, in <module> import main File "/tmp/workspaces/04497b9c-ee1c-47bc-9e15-b58ef0e5580c/main.py", line 2, in <module> import studentMain File "/tmp/workspaces/04497b9c-ee1c-47bc-9e15-b58ef0e5580c/studentMain.py", line 2, in <module> import algorithmsP2 File "/tmp/workspaces/04497b9c-ee1c-47bc-9e15-b58ef0e5580c/algorithmsP2.py", line 112, in <module> print ll.get_position(3).value AttributeError: 'NoneType' object has no attribute 'value'
解决方案
问题实际出在insert方法,而非最初以为的delete方法。原insert方法直接将current.next设为新元素,丢失了原本指向后续节点的引用,导致链表断裂。修改后的insert方法先保存原本的后续节点,再将新元素的next指向该节点,最后更新current.next为新元素,保证链表结构完整。
修改后的insert方法代码:
def insert(self, new_element, position): """Insert a new node at the given position. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements.""" current = self.head i = 1 if self.head: while i < position - 1: current = current.next i = i + 1 that = current.next new_element.next = that current.next = new_element while current.next: current = current.next else: self.head = new_element
内容的提问来源于stack exchange,提问作者Adxs
相关产品推荐
相关产品推荐

