将一个对象启动到另一个对象

  • 本文关键字:一个对象 启动 java
  • 更新时间 :
  • 英文 :


这是合并两个排序链表的代码。现在我的问题是给定的合并函数。为什么我们将new_node1引用new_node。直接在函数中使用new_node1而不是执行有什么问题 "节点 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);
}

唯一的区别是在最后一行,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);

这里

new_node1

是一个对象。

new_node

是一个引用变量,用于指向列表中的节点

最新更新