gpt4 book ai didi

python - 实现双向链表的问题

转载 作者:行者123 更新时间:2023-11-28 17:47:57 25 4
gpt4 key购买 nike

我正在制作双向链表类。

def remove(self, item):
current=self.__head
prev=None
found=False
if(self.__size>=1):
for i in range (0,self.__size):
if(current.getData()==item):
found=True
pos=i#save the position to pop
i=self.__size#leave the loop
else:
prev=current
current=current.getNext()

if(found==True):#excute only if the item is found
if(prev==None):#first item found
if(self.__size==1):
self.__head==None
self.__tail==None
current.setNext(None)
current.setPrevious(None)
else:#size bigger than 2
self.__head==current.getNext()
current.setNext(None)
else:
if(current.getNext()==None):#last item found
self.__tail==prev
current.setPrevious(None)
prev.setNext(None)
else:
Next=current.getNext()
current.setNext(None)
current.setPrevious(None)
Next.setPrevious(prev)
prev.setNext(Next)
self.pop(pos)
self.__size-=1

这就是我到目前为止所做的。如果我运行下面的代码

 for i in range(0, 10):
int_list2.add(i)
int_list2.remove(1)
int_list2.remove(3)
int_list2.remove(2)
int_list2.remove(0)
print(int_list2)

这些是我得到的输出

0

1

2

3

4 3

5 4 3

6 5 4 3

7 6 5 4 3

8 7 6 5 4 3

9 8 7 6 5 4

我希望前 4 行 (0~3) 不显示任何内容,从第 5 行开始显示为 4,第 6 行显示为 5 4...等等。

最后我想要 9 8 7 6 5 4

如何修复代码?

最佳答案

部分问题出在 for 循环中 if 语句的第一部分:

for i in range (0,self.__size):
if(current.getData()==item):
found=True
pos=i#save the position to pop
i=self.__size#<--- doesn't leave the loop
else:
prev=current
current=current.getNext()

设置i=self.__size 不会退出循环。请改用 break

这样一来,当您找到项目时,您会在循环中不断迭代,而 current 不是您要删除的项目。相反,current 是您在 for 循环中查看的最后一个节点的值。

当我确定你的意思是赋值 = 时,你也在使用 == 所以在这些行中:

self.__head==None   #should be self.__head=None
self.__tail==None #should be self.__tail=None
current.setNext(None)
current.setPrevious(None)

== 更改为单个 =。我想你在你的 if(found==True): block 中做了几次。这些行只是评估 bool 表达式并丢弃值。

更改这些内容,如果可以解决问题请告诉我。

还有一个小提示:

如果你有一个 bool 变量(比如 found),你不需要检查 found==True 因为它的计算结果与 相同发现。即:

if(found==True):
...

等同于:

if(found):
...

关于python - 实现双向链表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15261481/

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