2016-05-30 2 views
0

これは、ソートされた2つのリンクされたリストをマージするコードです。今私の質問は与えられたマージ関数にあります。 new_node1をnew_nodeに参照する理由関数内でnew_node1を直接使用するのではなく、何をするのですか? "Node new_node = new_node1;" (とにかく私は直接使用しようとしましたが、必要な出力を生成していません。単にマージされたリストの最後の項目を生成します)new_nodeオブジェクトはデフォルトのコンストラクタを使用しますか?精巧な説明は本当に役立つでしょう。事前に感謝します。他のオブジェクトへのオブジェクトの開始

static class Node{ 
    int data; 
    Node next; 
    Node(int num){ 
     data=num; 
     next=null; 
    } 
} 

// Function for merging two sorted linked list 

public void merge(Linkedlist list1,Linkedlist list2){  
    Linkedlist l=new Linkedlist(); 

    Node new_node1=new Node(0); 
    Node new_node=new_node1; //This line of code is my doubt! 
    while(list1.head!=null || list2.head!=null){  
     if(list1.head!=null && list2.head!=null){ 
     if(list1.head.data<=list2.head.data){ 
      new_node.next=list1.head; // what difference it makes by using new_node.next instead of new_node1 
      list1.head=list1.head.next;   

     } 
     else{ 
      new_node.next=list2.head; 
      list2.head=list2.head.next; 
      }   
     } 
     else if(list1.head==null){   
       new_node.next=list2.head; 
       list2.head=list2.head.next; 
      } 
     else if(list2.head==null){   
       new_node.next=list1.head; 
       list1.head=list1.head.next;     
     } 
     new_node=new_node.next; 
     //new_node1=new_node1.next; 
    } 
    l.printlist(new_node1); 

} 

答えて

0

唯一の違いは、最後の行にあるl.printlist(new_node1);です。ループの途中でnew_node1を使用すると、最後のノードが印刷されます。ループの途中でnew_nodeを使用すると、new_node1は変更されず、リストの先頭を指します。

new_node1からhead_nodenew_nodeからcurrent_nodeに名前を変更することをお勧めします。それは理解しやすくなります。ここで

Node head_node = new Node(0); 
Node current_node = head_node; 

// .. build the entire list of nodes .. 

l.printlist(head_node); 
+0

おかげでノードを指すために使用される参照変数です。私はそれを持って –

+0

そして、あなたはどのようなコンストラクタcurrent_nodeを使用して教えてください?それは私が定義されているコンストラクタまたはデフォルトのコンストラクタですか? –

+0

新しいオブジェクトは作成されません。コンストラクタは呼び出されません。両方の変数は、 'Node head_node = new Node(0);'行の同じオブジェクトを指します。 'current_node'は' head_node'が指し示すのと同じオブジェクトを指しています。 –

-1

new_node1 

がオブジェクトである:次に、あなたはこのような何かを得ます。

new_node 

間リスト

+0

あなたはJavaではなくCを考えているかもしれません。 –

+0

明らかでない場合: 'new_node1'も' new_node'もそれ自体オブジェクトではありません。どちらもオブジェクトへの参照です。最初は、同じオブジェクトへの参照です。ループを通る各反復の最後に、 'new_node'は新しいオブジェクトへの参照になり、' new_node1'は元の参照のままです。 –

+1

さようなら!ありがとうございました –

関連する問題