实施双向链表的问题

时间:2013-03-07 01:31:23

标签: python linked-list 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行为5 4 ....依此类推。

最后我想要9 8 7 6 5 4

如何修复代码?

1 个答案:

答案 0 :(得分:2)

部分问题出在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):
   ...
相关问题