2013-02-23 103 views
0

剛開始,這是作業,所以我只是在這裏尋找提示。我對Python和編程一般都很陌生。我應該實現雙重鏈接的基於光標的列表。我在插入列表時遇到了一些麻煩。我的教師提供了一個簡單的Node類和Node2Way類。他還提供了init方法:Python 3插入雙鏈表

from node import Node 

class Node2Way(Node): 
    def __init__(self,initdata): 
     Node.__init__(self,initdata) 
     self.previous = None 

    def getPrevious(self): 
     return self.previous 

    def setPrevious(self,newprevious): 
     self.previous = newprevious 

這裏是我迄今爲止(只是相關的方法):

from node2way import Node2Way 

class CursorBasedList(object): 
    """ Linked implementation of a positional list.""" 

    def __init__(self): 
     """ Creates an empty cursor-based list.""" 
     self._header = Node2Way(None) 
     self._trailer = Node2Way(None) 
     self._trailer.setPrevious(self._header) 
     self._header.setNext(self._trailer) 
     self._current = None 
     self._size = 0 

def insertAfter(self, item): 
     """Inserts item after the current item, or 
     as the only item if the list is empty. The new item is the 
     current item.""" 
     temp = Node2Way(item) 
     if self.isEmpty(): 
      self._header.setNext(temp) 
      self._trailer.setPrevious(temp) 
     else: 
      temp.setNext(self._current.getNext()) 
      self._current.setNext(temp) 
      temp.setPrevious(self._current) 
     self._current = temp 
     self._size+=1 

當我測試的insertAfter方法了,它適用於添加的第一個項目,但是當我嘗試添加第二個項目時,它說self._current是None類型,不能使用getNext方法。我不知道是否有另一種方法可以在當前節點之後獲取臨時節點的引用。我不確定我做錯了什麼,或者即使我做的任何事情都是對的。我想一旦我得到了insertAfter方法,我會很好地用insertBefore方法。

任何提示將不勝感激。先謝謝你! :)

+0

嘿,你可以發佈代碼,你實際上插入到'CursorBasedList()',以及錯誤消息? – 2013-02-23 23:12:32

回答

1

if self.isEmpty(): 
     self._header.setNext(temp) 
     self._trailer.setPrevious(temp) 

你從未設置的temp一個和下一個節點的情況。

+0

感謝您的提示。我只是在理解鏈表時遇到一些麻煩。 :\ – AbigailB 2013-02-23 20:58:35