これは、ソートされた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);
}
おかげでノードを指すために使用される参照変数です。私はそれを持って –
そして、あなたはどのようなコンストラクタcurrent_nodeを使用して教えてください?それは私が定義されているコンストラクタまたはデフォルトのコンストラクタですか? –
新しいオブジェクトは作成されません。コンストラクタは呼び出されません。両方の変数は、 'Node head_node = new Node(0);'行の同じオブジェクトを指します。 'current_node'は' head_node'が指し示すのと同じオブジェクトを指しています。 –