0

我正在尝试根据 CLRS 书编写一个包含哨兵的链接列表。由于某种原因,我的删除功能将一大块 LL 删除到要删除的节点。附上我的代码。任何建议将不胜感激。

class Node():
    def __init__(self,v):
        self.value = v
        self.next = None
        self.prev = None

    def getValue(self):
        return self.value

    def changeValue(self,v):
        self.value = v

    def getNext(self):
        return self.next

    def getPrev(self):
        return self.prev

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

    def setPrev(self,newPrev):
        self.prev = newPrev

class List(Node):
    def __init__(self):
        self.nil = Node(None)

    def addNode(self,v):
        a = Node(v)
        a.setNext(self.nil.next)
        a.setPrev(self.nil)
        self.nil.next = a

    def length(self):
        count = 0
        a = self.nil
        while(a.next != None):
            count += 1
            a = a.getNext()
        return count

    def search(self,v):
        a = self.nil
        while(a.next != None):
            if (a.value == v):
                return True
            a = a.getNext()
        return False

    def remove(self,v):
        a = self.nil.next
        breakloop = 0
        while((a.next != None) and (breakloop == 0)):
            if (a.value == v):
                a.prev.next = a.next
                a.next.prev = a.prev
                breakloop = 1
            a = a.getNext()

    def printList(self):
        a = self.nil.next
        while(a.next != None):
            print(a.value)
            a =a.getNext()
        print(a.value)


a = List()
a.addNode(4)
a.addNode(7)
a.addNode(2)
a.addNode(6)
a.addNode(5)
a.addNode(8)
a.addNode(1)
a.addNode(14)
a.addNode(13)
a.addNode(17)
a.addNode(18)
a.printList()
a.remove(13)
a.printList()

输出将是
18 17 13 14 1 8 5 6 2 7 4
14 1 8 5 6 2 7 4

4

2 回答 2

2

@tcaswell 已正确诊断出代码问题:您没有prev在节点上设置曾经正确的链接self.nil.next。但是,我认为他的解决方案并不理想。这是我的建议:

这是该问题的直接解决方法:

def addNode(self, v):
    a = Node(v)

    a.setNext(self.nil.next)
    self.nil.next.setPrev(a) # this is the link that was previously missing

    a.setPrev(self.nil)
    self.nil.setNext(a)

但是,当列表为空时,这将无法正常工作,因为self.nil.nextNone开始时。不过,我们可以通过在构造函数self.nil中创建它时链接到自身来修复它:List

def __init__(self):
    self.nil = Node(None)
    self.nil.next = self.nil.prev = self.nil # set up circular links!

现在,self.nil将始终有一个有效的节点,因为它是nextprev值。

您将需要更改您的removeNodeandprintList循环以检查self.nil而不是None.

于 2013-02-16T05:11:58.163 回答
1

错误在您的addNode函数中,所有.prev节点的节点都是self.nil

使用以下内容:

def addNode(self,v):
    a = Node(v)
    a.setNext(self.nil.next)
    if self.nil.next is not None:
        self.nil.next.setPrev(a)
    a.setPrev(self.nil)
    self.nil.next = a

将解决您的问题。您可能希望将此逻辑放在setPrevandsetNext函数中(以确保始终适用于除末端之外的所有内容)a == a.next.preva == a.prev.nexta

于 2013-02-16T04:50:20.887 回答