2016-04-19 9 views
0

Pythonでリンクされたリスト(ノード)。これは可能ですか?Pythonでリンクされたリスト(ノード)

私が見つけた次の例を試しています。

各ノードには「次へ」があるので、リストを作成すると仮定しています。

次のように私は取得していた結果は次のとおりです。

$ python linked.py 
Traceback (most recent call last): 
    File "linked.py", line 40, in <module> 
    insertAtBeginning("test1") 
TypeError: insertAtBeginning() takes exactly 2 arguments (1 given) 


#Node of a Singly Linked List 
class Node: 
    #constructor 
    def __init__(self): 
    self.data=None 
    self.next=None 

    #method for setting the data field of the node 
    def setData(self,data): 
    self.data=data 

    #method for getting the data field of the node 
    def getData(self,data): 
    return self.data 

    #method for setting the next field of the node 
    def setNext(self,next): 
    self.next=next 

    #method for getting the next field of the node 
    def getNext(self,next): 
    return self.next 

    #returns true if the node points to another node 
    def hasNext(self): 
    return self.next != None 

def insertAtBeginning(self,data): 
    newNode=Node() 
    newNode.setData(data) 

    if self.length==0: 
    self.head=newNode 
    else: 
    newNode.setNext(self.head) 
    self.head=newNode 

    self.length+=1 

insertAtBeginning("test1") 
insertAtBeginning("test2") 
+0

あなたはJavaを考えており、Python構文でコーディングしています。これは醜いです、私はそれが好きではありません。 –

+0

このコードは「データ構造とアルゴリズムによるPythonの考え方」という本から来たものです –

+1

それを書いた人がEinsteinかMartijn Pietersであっても、それは醜いです。例えば、ゲッタやセッタはpythonicではありません。 –

答えて

1
def insertAtBeginning(self,data): 

メソッド宣言にタブが不足している自己のインスタンスをオブジェクトへ解決しない理由、それはです。

また、あなたのリストの頭があなたのノードクラス外で開催されなければならない、そうでない場合は、リストのすべての要素を追加するために、長さを追跡する必要はありません新しいヘッド

で更新する必要があります頭の位置にある要素。

アルゴリズムはかなり単純です:

if myListHead == none: 
    myListHead = new Node() 
else: 
    myNewHead = new Node() 
    myNewHead.next = myListHead 
    myListHead = myNewHead 

これで擬似Pythonのコード...

0

I「は「現在のインスタンスの略で、単に「本」で他の言語のように、ここで「自己」 m個の」クラスのない任意のタイプ、

関数はクラス内で定義されたのであれば、まず、それがself.insertAtBeginように呼ばれるべきである( 『バラ』)は

secon d、これがノードインスタンスまたはデータ構造のシーケンスを管理しようとする別の関数jusrの場合、入力パラメータとして "self"を使用しないでください。それは保存されたキーワード、おそらく "node"などです。

0

LinkedListのクラスが見つからなかったため、著者にはこれが含まれていませんでした。

これはfindであり、関数はノードクラスではなくLinkedListクラスにあります。

class LinkedList: 
    #constructor 
    def __init__(self): 
    self.head=None 
    self.length=0 

    def insertAtBeginning(self,data): 
    newNode=Node() 
    newNode.setData(data) 

    if self.length==0: 
     self.head=newNode 
    else: 
     newNode.setNext(self.head) 
     self.head=newNode 

    self.length+=1 

    def printList(self): 
    current=self.head 
    while current.getNext() != None: 
     print current.data 
     current=current.getNext() 

    print current.data 

newList=LinkedList() 
newList.insertAtBeginning("test") 
newList.insertAtBeginning("test123") 
newList.printList() 
関連する問題