2017-02-07 36 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

糟糕......忘了最初没有任何东西,这只会有助于遍历列表。 –