[英]Python Linked List - insert method
我對 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
插入 function 正在替換當前節點而不是鏈接它。 我將用一個例子來說明這一點:
我有這個鏈表:1 -> 2 -> 3 我想在 position 1 中插入一個元素“4”(position 1 中的當前數字是 2)。 迭代將是:
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)
之后代碼繼續如下:
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
使用以下代碼進行了測試,並且可以正常工作:
a = LinkedList()
a.append(1)
a.append(2)
a.append(3)
a.insert(0, 4)
a.insert(1, 5)
print(a.display())
鏈表沒有索引,所以不需要從 index=0 開始。 同樣對於鏈表,有 3 種插入方法,insert_to_first、insert_to_last 或 insert_to_any_position。 您正在實施 insert_to_any position。
def insert(self, index, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.