2016-04-10 20 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. süresi. Bundan sonra üç kez üye fonksiyonunu add_node() çağırıyorum.
  2. ancak list_print işlevini çağırdığımda, 3-> 2-> 1 yazdırır.piton sınıf nesnesi ve değişkenleri linked_list sınıfının nesne oluşturma

  3. Sorum şu: Bu nasıl yazdırılıyor? bana göre "3" sadece yazdırmak gerekir çünkü ben ll.list_print() dediğimde, self.cur_node değeri 3'e eşittir. Bu nedenle, üç girdiyi de nasıl yazdırıyor. Önceki değerleri "2,1" nerede saklıyor? lütfen bana yardım edin.
+1

Bir yazdırma deyimi olmadan bir şeyler yazdırmak nasıl merak ediyorum içinde ilerlemeyi kontrol etmek için bir baskı ekledik. – timgeb

+1

@SMSvonderTann, ancak bu kodda da değil. – timgeb

+0

@timgeb Doğru, bu kod ve OP'nin şu anda ne istediği ile kafam karışıyor. –

cevap

0

Add_note yönteminde, bu son önce bildirilmeden önce new_node.next = self.cur_node bildiriyorsunuz, ancak bu gereksizdir. Bu satırı yorumlayın! Ben bu yöntemle

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

İlgili konular