2016-04-10 9 views
-2
class Node: 
    def __init__(self): 
     self.data = None # contains the data 
     self.next = None # contains the reference to the next node 


class linked_list: 
    def __init__(self): 
     self.cur_node = None 
     self.counter = 0 


    def add_node(self, data): 
     new_node = Node() # create a new node 
     new_node.data = data 
     new_node.next = self.cur_node # link the new node to the' previous' node. 
     self.cur_node = new_node # set the current node to the new one. 

    def list_print(self): 
     node = self.cur_node # cant point to ll! 
     while node: 
      print node.data 
      node = node.next 




ll = linked_list() 

ll.add_node(1) 
ll.add_node(2) 
ll.add_node(3) 
ll.list_print() 
  1. 私はlinked_listクラスのオブジェクトを作成しています。
  2. その後、メンバー関数add_node()を3回呼び出しています。Pythonクラスのオブジェクトと変数のライフタイム

  3. ですが、関数list_printを呼び出すと、3 - > 2-> 1が出力されます。

  4. 私の質問はここにありますそれはどのようにそれを印刷ですか?私によれば、ll.list_print()を呼び出すとself.cur_nodeの値が3に等しいので、 "3"だけを出力するはずです。以前の値 "2,1"はどこに保存されていますか?私を助けてください。
+1

あなたはprint文なしで何かを印刷する方法を、私は好奇心の中に進行状況を確認するために、プリントを追加しました。 – timgeb

+1

@SMSvonderTann確かに、それはコードにもありません。 – timgeb

+0

@timgebそうですね、私はこのコードとあとでOPが望んでいることで混乱してしまいます。 –

答えて

0

add_noteメソッドでは、これを最後に宣言する前にnew_node.next =をself.cur_nodeに宣言していますが、これは不要です。その行にコメントしてください!私はその方法

class Node: 
    def __init__(self): 
     self.data = None # contains the data 
     self.next = None # contains the reference to the next node 


class linked_list: 

    def __init__(self): 
     self.cur_node = None 
     self.counter = 0 

    def add_node(self, data): 
     new_node = Node() # create a new node 
     new_node.data = data 
     #new_node.next = self.cur_node # link the new node to the' previous' node. 
     print(self.cur_node) 
     self.cur_node = new_node # set the current node to the new one. 

    def list_print(self): 
     node = self.cur_node # cant point to ll! 
     while node: 
      print node.data 
      node = node.next 

ll = linked_list() 
ll.add_node(1) 
ll.add_node(2) 
ll.add_node(3) 
ll.list_print() 

enter image description here

関連する問題