我正在尝试根据 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