gpt4 book ai didi

python - 在python链表的第N个位置插入一个节点

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:24 24 4
gpt4 key购买 nike

我试图在链表的“index”位置插入一个节点“item”,我有以下代码,对我来说它听起来不错,但它不能正常工作。

如果有人能帮助我,我将不胜感激。

class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None

def getData(self):
return self.data

def getNext(self):
return self.next

def setData(self,newdata):
self.data = newdata

def setNext(self,newnext):
self.next = newnext

然后我有:

class UnorderedList:
def __init__(self):
self.head = None

def isEmpty(self):
return self.head ==None

def add(self,newdata):
Temp = Node(newdata)
# What happens here: the Temp.Next is going to connect to the place that head is connected to
Temp.setNext(self.head)
self.head = Temp


def printl(self):
current = self.head
i=""
while current.getNext() != None:
i =i+ "-"+str(current.getData())
current= current.getNext()
i =i+ "-"+str(current.getData())
return i

def insert(self,item,index):
current = self.head
counter = 0
Temp = Node(item)

Prev = None

if index == 0:
Temp.setNext(self.head)
self.head = Temp
else:
while counter < index:
Prev = current
current = current.getNext()
counter = counter + 1

Temp.setNext(Prev.getNext())
Prev.setNext(Temp.getNext())
current.setData = Temp

所以我在这里做一些测试:

mylist = UnorderedList()
mylist.insert(54,0)
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
print(mylist.printl())
mylist.insert(12,2)
print(mylist.printl())

输出是:

-26-93-17-77-31-54
-26-93-17-77-31-54

如您所见,节点未添加。您能告诉我我的代码有什么问题以及我该如何解决吗?

最佳答案

insert函数中,应该是Prev.setNext(Temp),previous'next必须是要插入的,而不是下一个:

    def insert(self,item,index):
current = self.head
counter = 0
Temp = Node(item)

Prev = None

if index == 0:
Temp.setNext(self.head)
self.head = Temp
else:
while counter < index:
Prev = current
current = current.getNext()
counter = counter + 1

Temp.setNext(Prev.getNext())
Prev.setNext(Temp)
current.setData = Temp

关于python - 在python链表的第N个位置插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46350266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com