[英]Issues with implementing a doubly-linked list
我正在制作雙向列表類。
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第1行為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):
塊中做了幾次。 這些行只是評估布爾表達式並拋棄值。
更改這些內容,如果能解決問題,請告訴我。
還有一點小貼士:
如果你有一個布爾變量(如found
),則不需要檢查found==True
因為它的計算結果與剛剛found
值相同。 即:
if(found==True):
...
是相同的:
if(found):
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.