我在下面的代碼中運行以從鏈接列表中刪除重複項。但是我的代碼在刪除重複項之前僅打印鏈接列表。一旦調用removeDup方法,它不會打印任何東西。以下是我的代碼。請告訴我我錯過了什麼。從鏈接列表中刪除重複項Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
node = Node(data)
node.next=self.head
self.head = node
def printl(self):
current = self.head
while current:
print current.data
current= current.next
def removeDups(self):
current = self.head
while current is not None:
second = current.next
while second:
if second.data == current.data:
current.next = second.next.next
second = second.next
current = current.next
# l.printl()
l= LinkedList()
l.insert(15)
l.insert(14)
l.insert(16)
l.insert(15)
l.insert(15)
l.insert(14)
l.insert(18)
l.insert(159)
l.insert(12)
l.insert(10)
l.insert(15)
l.insert(14)
l.printl()
print "==============="
l.removeDups()
l.printl()
我仍然沒有得到它如何切除其他元素。 –
在紙上(或在電子白板上)寫出鏈接列表通常很有幫助。嘗試一個列表,比如'1 - > 2 - > 3 - > 1 - > 4',並在通過算法時爲'current'和'second'繪製額外的箭頭。例如,當'current'指向第一個節點(第一個'1'),並且'second'指向'3'節點時,您將檢查兩個'1'值是否相等,並且然後將'3'節點鏈接到'4'節點(切出複製的'1')。 – Blckknght
謝謝你的幫助...... –