2017-02-07 38 views
-1

我解決了這個問題,但在此之前,我正在嘗試其他方法無效。Python鏈表黑客排名

def insert(self,head,data): 
    if (head == None): 
     head = Node(data) 
    else: 
     current = head 
     while current != None: 
      current = current.next 
     current = Node(data) 
    return head 

這是我做的第一個,然後我做了這個

def insert(self,head,data): 
    if (head == None): 
     head = Node(data) 
    else: 
     current = head 
     while True: 
      if(current.next == None): 
       current.next = Node(data) 
       break 
      current = current.next 
    return head 

這裏是鏈接的問題https://www.hackerrank.com/challenges/30-linked-list

+2

你的問題是什麼? – MooingRawr

回答

0

那麼顯然,這是行不通的,因爲在這裏:

current = head 
while current != None: 
    current = current.next 
current = Node(data) 

you iterate until currentNone,則創建一個新節點並將本地變量current設置爲該節點。然而,前面的next **仍然是None。因此您需要設置以前的next。例如你可以做到這一點與:

current = head 
while current.next != None: 
    current = current.next 
current.next = Node(data)

A小調的改進是使用is not None而不是!= None:因爲只有一個None你可以使用引用相等(is)。

+0

糟糕......忘了最初沒有任何東西,這隻會有助於遍歷列表。 –