2017-06-06 55 views
-1

以下是在python.Only從頭創建一個鏈表的代碼追加功能都是在這裏完成:下面的鏈表如何在Python中工作?

class Element(object): 
    def __init__(self, value): 
     self.value = value 
     self.next = None 
class LinkedList(object): 

    def __init__(self, head=None): 
     self.head = head 

    def append(self, new_element): 
     current = self.head 
     if self.head: 
      while current.next: 
       current = current.next 
      current.next = new_element 
     else: 
      self.head = new_element 

我完全不懂行是如何工作的

  current = current.next 
     current.next = new_element 

我認識到,第一行是沿着鏈表移動(就像增量一樣),第二行是將前一個節點的地址鏈接到鏈表的下一個元素。但是有人可以解釋一下如何在更深層次上實際工作如何分配什麼(它們是什麼類型的變量,賦值地址或值)

+3

你問如何Python的變量/分配工作? –

+0

只是閱讀這個:https://nedbatchelder.com/text/names.html –

+1

你在找什麼樣的答案? LinkedList對象只保留對第一個元素的引用。爲了追加,while循環需要遵循所有'next'鏈接才能找到最後一個。 –

回答

1

well'current=current.next語句表示您將要在其下一個字段中包含無地址的節點,因爲這將成爲鏈接列表的終止節點,之後您必須添加將由聲明current.next=element(7)見下方給出的程序會告訴你如何在Python中創建一個單向鏈表...希望它可以幫助你....和insertion at beginning or any other position in linked list click here

class Node: 
    def __init__(self,data,next=None): 
    self.data=data 
    self.next=None 

class LinkedList(): 
    def __init__(self): 
    self.head=None 

    def insert(self,data): 
     if(self.head==None): 
     n=Node(data) 
     self.head=n 
     return 
     else: 
     current=self.head 
     while(current.next!=None): 
      current=current.next 
     current.next=Node(data) 
     return 
    def printing(self): 
     if(self.head==None): 
     print "Linked List is empty" 
     else: 
     current=self.head 
     while(current!=None): 
      print current.data, 
      current=current.next 
myLinkList=LinkedList() 
myLinkList.insert(18) 
myLinkList.insert(20) 
myLinkList.insert(56) 
myLinkList.insert(50) 
print("\n\nThe created Singly Linked List is: \n\n") 
myLinkList.printing() 
print("\n\n") 
+0

非常感謝。我明白你在說什麼,我想知道的是地址的工作方式。我發現這個偉大的資源幫助我加強了我的理解。 http://pythontutor.com –