我在刪除鏈表中所有相同值的實例時遇到了很多麻煩。我明白這個問題與remove函數的self.head部分有關。刪除指定值的所有實例的鏈接列表
class Node:
def __init__(self,data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
#Checks to see if the list is empty
def isEmpty(self):
return self.head == None
#Adds the item at the beginning of the list
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
#Prints the Unordered List
def __str__(self):
result = "["
current = self.head
if current != None:
result += str(current.data)
current = current.next
while current:
result += ", " + str(current.data)
current = current.next
result += "]"
return result
# Removes a specified item from the list
def remove(self, item):
if self.head == None:
return 'Cannot remove from an empty list'
current = self.head
while current != None:
iterator = current
while iterator != None:
prev = iterator
iterator = iterator.getNext()
if iterator is None:
break
if iterator.getData() == item:
Next = iterator.getNext()
prev.setNext(Next)
current = current.getNext()
mylist = UnorderedList()
for i in range(50):
mylist.add(2)
mylist.remove(2)
print(mylist)
結果:2,2,2,2,2]
預期的結果:[]
是的,我喜歡提出異常的建議。我失去了爲什麼第三條語句(如果self.head不是None)跑到無窮大。例如,這輸入MYLIST下= UnorderedList() 爲i的範圍(50): mylist.add(2) mylist.add(31) mylist.add(77) mylist.add(17) MYLIST 。新增(93) mylist.add(26) mylist.add(31) mylist.add(54) 打印(MYLIST) mylist.remove(2) 打印(MYLIST) – skryt
噢,它運行永遠因爲我很笨拙,並且沒有任何代碼將'current'推進到後面的節點。您只希望在不僅僅是移除某件物品時發生這種情況。我編輯了希望不會永遠運行的代碼。 – Blckknght