简体   繁体   English

使用 Python 实现双向链表

[英]Doubly linked list with Python

I'm trying to implement doubly linked list in python but am not able to implement deletion properly.我正在尝试在 python 中实现双向链表,但无法正确实现删除。

def deleteFromBeginning(self):
    if self.listLength()==0:
        print("Can't delete from an empty list")
    else:
        self.head = self.head.next

def deleteFromEnd(self):
    if self.listLength() ==0:
        print("Can't delete from an empty list")
    else:

        current=self.head
        while(current.next!=None):
            current.prev = current
            current = current.next

        current.prev.next = None
        current.prev = None

def deleteFromPosition(self,pos):
    if pos> self.listLength() or pos<0:
        ValueError("Enter a valid position")
    elif pos==0:
        deleteFromBeginning()
    elif pos == self.listLength():
        deleteFromEnd()
    else:
        if self.listLength()==0:
            print("Can't delete from an empty list")
        else:
            current=self.head
            count = 1
            while(current.next!=None and count<pos):
                current = current.next
                count = count+1

            current.prev.setNext(current.next)
            current.next.setPrev(current.prev)
            current.setPrev(None)
            current.setNext(None)

def deleteWithData(self,data):
    if self.listLength()==0:
        ValueError("Can't delete from an empty list")
    else:
        current = self.head
        while current.next!=None:
            if current.data == data:
                current.prev.next = current.next
                current.next.prev = current.prev
                return
            else:
                current = current.next
        print("The value provided is not present")

The deletion from beginning and end works fine but deletion with position and data are not giving the desired results.从头到尾的删除工作正常,但删除位置和数据并没有给出预期的结果。 输出截图

One slight refactoring I would do is move your我会做的一个轻微的重构是移动你的

if self.listLength()==0:
            print("Can't delete from an empty list")

check to the very top, and not inside the else.检查到最顶部,而不是在 else 内部。 This should be one of the very first checks you make.这应该是您首先进行的检查之一。

Other than that, what you can try is keep a track of the previous node:除此之外,您可以尝试跟踪前一个节点:

while(current.next!=None and count<pos):
                temp = current
                current = current.next
                count = count+1

        temp.setNext(current.next)
        current.next.setPrev(temp)

This should remove the node in the x position, by relinking the previous node to the next node.这应该通过将前一个节点重新链接到下一个节点来删除 x 位置的节点。

Haven't tested it, let me know how it goes!还没有测试过,让我知道它是怎么回事!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM