2016-06-28 13 views
0

リンクリスト2の終わりにリンクリスト2をマージするはずのコードで何が欠けているのかを理解しようとしています。今すぐ2番目のリストの最後の要素を取得しています。それを返す。Javaを使用して2つのリンクリストを結合する

私が使用しようとしていたロジックは、最初のリスト(L1)を歩いていて、それらの要素を1つずつnew_listに追加してから、2番目のリスト(L2)に対して同じことをやっています。 L1。私はL1やL2の変更を避けようとしています。これがnew_listを作成した理由です。

ご協力いただければ幸いです。

public NodeList(int item, NodeList next) { 
    this.item = item; 
    this.next = next; 
} 

public static NodeList merge(NodeList l1, NodeList l2) { 

    NodeList new_list = new NodeList(l1.item, l1.next); 
    NodeList new_list2 = new NodeList(l2.item, l2.next); 

    while (true) { 
     if (new_list.next == null) { 
      if (new_list2.next == null) { 
       return new_list; 
      } 
      else { 
       new_list.next = new NodeList(new_list2.next.item, new_list2.next.next); 
       new_list2 = new_list2.next; 
      } 

     } 
     else { 
      new_list.next = new NodeList(new_list.next.item, new_list.next.next); 
      new_list = new_list.next; 
     } 
    } 
} 
+0

あなたのwhileループは決して終了しません –

+2

'Node'と' NodeList'の概念を混在させているようです。 –

+0

@SeanPatrickFloyd両方のリストがnullの場合、コードは呼び出し元のメソッドに戻ります。 – azurefrog

答えて

2

リストの最初のノードへの参照を保持する必要があります。以下の例では、ループを所定の終了条件で2つのループに分割しています。これは論理的に実行しようとしているためです。既存のリストの要素への参照は決して変更したくないと述べたので、決してコピーしないことに注意してください。しかし私は、入力へのローカル参照インクリメントん:あなたが見ることができるように

public static NodeList merge(NodeList l1, NodeList l2) { 

    NodeList new_head = new NodeList(0, null); 
    NodeList new_node = new_head; 

    for(; l1 != null; l1 = l1.next) { 
     new_node.next = new NodeList(l1.item, null); 
     new_node = new_node.next; 
    } 

    for(; l2 != null; l2 = l2.next) { 
     new_node.next = new NodeList(l2.item, null); 
     new_node = new_node.next; 
    } 
    return new_head.next; 
} 

が、これはコードの繰り返しをたくさん持っているが、それは簡単にリストの任意の数のために一般化することができます。

public static NodeList merge(NodeList... l) { 

    NodeList new_head = new NodeList(0, null); 
    NodeList new_node = new_head; 

    for(NodeList ln in l) { 
     for(; ln != null; ln = ln.next) { 
      new_node.next = new NodeList(ln.item, null); 
      new_node = new_node.next; 
     } 
    } 
    return new_head.next; 
} 
+0

ああ、ありがとう!私がやろうとしていたものよりもはるかに明確です。 –

関連する問題