2017-01-14 12 views
0

この質問はハッカーの挑戦です。ここにリンク:https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list特定の場所にノードを挿入するpython

""" 
Insert Node at a specific position in a linked list 
head input could be None as well for empty list 
Node is defined as 

class Node(object): 

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

return back the head of the linked list in the below method. 
""" 
#This is a "method-only" submission. 
#You only need to complete this method. 
def InsertNth(head, data, position): 
    node = head 
    if position == 0: 
     node = Node(data) 
     node.data = data 
     node.next = head 
     return node 
    else: 
     while position > 0: 
      node = node.next 

      i = node.next 
      node.next = Node(data) 
      node.next.next = i 
      return head 

私の現在の出力は321024ですが、私はそれがすべてのヘルプは大歓迎です310542.する必要があります!

+0

あなたの 'while'ループは意味をなさない。常に正確に1回実行されます。 –

答えて

3
def InsertNth(head, data, position): 
    start = head 
    if position == 0: 
     return Node(data, head) 
    while position > 1: 
     head = head.next 
     position -= 1 
    head.next = Node(data, head.next) 
    return start 

私はテストしませんでしたが、このようなものは正しいはずです。まず、参照のコピーをリストの先頭に保存します。次に、これがリストの先頭に追加されているかどうかを確認する必要があります。その場合は、適切な値で新しい開始ノードを返す必要があります。それ以外の場合は、次のノードに適切な値と残りのリストを設定するポイントになるまで、リスト内を循環します。

+0

できれば1をプラスします。この説明が役立ちます、あなたに感謝@ Vedranh13。それはbtwを動作させます。 – Johnny

関連する問題