如何解决Python 链表 - 插入方法
我对 DataStructure 有点陌生,我正在尝试编写 LinkedList,但我不知道为什么我的插入方法不起作用。如果您有任何改进建议,请写信给我
class Node:
def __init__(self,data):
self.item = data
self.ref = None
class LinkedList:
def __init__(self):
self.start_node = None
self.index = 0
def append(self,val):
new = Node(val)
if not self.start_node:
self.start_node = new
return
last = self.start_node
while last.ref:
last = last.ref
last.ref = new
self.index += 1
def insert(self,index,value):
start_counting = 0
start = self.start_node
while start_counting < index:
start = start.ref
start_counting += 1
NewNode = Node(value)
tmp = start.ref
start = NewNode
start.ref = tmp
def display(self):
ls = []
last = self.start_node
while last:
ls.append(last.item)
last = last.ref
return ls
解决方法
插入函数正在替换当前节点而不是链接它。我会用一个例子来说明这一点:
我有这个链表:1 -> 2 -> 3 我想在位置 1 插入一个元素“4”(位置 1 的当前数字是 2)。 迭代将是:
list = [{"foo1": 1},{"foo2": 3},{"foo1": 6},{"foo2": 0},{"foo2": 1},{"bar1": 1},]
第一次迭代:
start_counting = 0
start = self.start_node (node with value 1)
第二次迭代:
start_counting < 1 -> true
start = start.ref (node with value 2)
start_counting += 1 (actual count 1)
之后代码继续如下:
start_counting < 1 -> false
start = (node with value 2)
要修复错误,您应该考虑两件事:
- 迭代到前一个节点而不是下一个。
- 处理你想插入一个节点作为链表头的情况,换句话说,在位置 0。
代码类似于:
We create the new Node (4 in my example) and we do:
tmp = start.ref (which is 3)
start = NewNode (we are replacing the node completely,we are not linking the node with another) <- here is the error
start.ref = tmp (which in this case is 3)
使用以下代码进行测试,它可以工作:
def insert(self,index,value):
start_counting = 0
start = self.start_node
NewNode = Node(value)
if index == 0: # Handling the position 0 case.
NewNode.ref = start
self.start_node = NewNode
else:
while start_counting < index - 1: # Iterating until the previous node.
start_counting += 1
start = start.ref
NewNode.ref = start.ref
start.ref = NewNode
,
链表没有索引,所以不需要从index=0开始。同样对于链表,有 3 种插入方法,insert_to_first、insert_to_last 或 insert_to_any_position。您正在实施 insert_to_any 位置。
def insert(self,value):
start_counting = 0
start = self.start_node
while start_counting < index:
start = start.ref
start_counting += 1
# so far no issue
NewNode = Node(value,None) # new Node accepts 2 args
# Let's write a linked list to visualize
# A->B->C-> adding_Node_Here ->D->E... make sure we dont lose ref to D when we inser
# after while loop,we end up start=C
NewNode.ref=start.ref # we keep the ref to D
start.ref=NewNode # now C refs to NewNode
self.index+=1 # again linked list is not indexed. "size" is better term
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。