2017-09-21 110 views
1

我想在鏈接列表中的位置「index」中插入節點「item」,我有以下代碼,對我來說聽起來不錯,但它不是正確的工作。在python鏈接列表中的第N個位置插入一個節點

我真的很感激,如果有人可以幫助我。

class Node: 
    def __init__(self,initdata): 
     self.data = initdata 
     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 

    def isEmpty(self): 
     return self.head ==None 

    def add(self,newdata): 
     Temp = Node(newdata) 
     #   What happens here: the Temp.Next is going to connect to the place that head is connected to 
     Temp.setNext(self.head) 
     self.head = Temp 


    def printl(self): 
     current = self.head 
     i="" 
     while current.getNext() != None: 
      i =i+ "-"+str(current.getData()) 
      current= current.getNext() 
     i =i+ "-"+str(current.getData()) 
     return i 

    def insert(self,item,index): 
     current = self.head 
     counter = 0 
     Temp = Node(item) 

     Prev = None 

     if index == 0: 
      Temp.setNext(self.head) 
      self.head = Temp 
     else: 
      while counter < index: 
       Prev = current 
       current = current.getNext() 
       counter = counter + 1 

       Temp.setNext(Prev.getNext()) 
       Prev.setNext(Temp.getNext()) 
       current.setData = Temp 

所以我在這裏做了一些測試:

mylist = UnorderedList() 
mylist.insert(54,0) 
mylist.add(31) 
mylist.add(77) 
mylist.add(17) 
mylist.add(93) 
mylist.add(26) 
print(mylist.printl()) 
mylist.insert(12,2) 
print(mylist.printl()) 

,輸出是:

-26-93-17-77-31-54 
-26-93-17-77-31-54 

正如你所看到的節點不被添加。 你能告訴我我的代碼有什麼問題,以及我如何修復它?

回答

2

insert功能,它應該是Prev.setNext(Temp),之前的未來必須要插入的一個,而不是它的未來:

def insert(self,item,index): 
     current = self.head 
     counter = 0 
     Temp = Node(item) 

     Prev = None 

     if index == 0: 
      Temp.setNext(self.head) 
      self.head = Temp 
     else: 
      while counter < index: 
       Prev = current 
       current = current.getNext() 
       counter = counter + 1 

      Temp.setNext(Prev.getNext()) 
      Prev.setNext(Temp) 
      current.setData = Temp 
+1

我不認爲我們不需要最後一行「current.setData = Temp 「 – Albert

相關問題