2017-04-15 8 views
0

私は私がunderstand.myクラスがリンクリストのJava refernce

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

でいけないと私はいけない

public static Node insert(Node head,int data) { 
    Node current = head; 

    if(head!=null){ 
    while(current.next!=null){ 
     current = current.next; 
    } 

    current.next = new Node(data); 

    return head; 
    } else { 
    return head=new Node(data); 
    } 
} 

事を挿入するFNを持ってimplementation.But一部リンクリストのJavaを得ました頭が現在の変数に設定されていることを理解しています。 を呼び出し、次のノードを現在のオブジェクトに渡して渡します。

私の質問現在は頭の基準がありますので、技術的に別の値を割り当てると、頭が変わります。私はint data.ifと私は頭に影響を受ける参照してくださいcurrent.dataを更新することができます..

ここで起こっていることを理解するのを助けてください...

答えて

0

基本的にこの関数は、リンクされたリストコレクションのHEAD要素として新しい要素を追加しています。すべての要素はNEXT要素への参照を持っているので、次の要素が存在しない場合はそれを走査し、新しい要素(関数に渡したデータを持つ)に設定します。 私はあなたの懸念を理解しているかどうかはわかりませんが、 "現在の"変数を変更することで、単に "参照"をオブジェクトに変更するだけで、オブジェクト自体は変更しません。したがって、次のアイテムが存在しない場合は、参照を変更して新しいオブジェクトを作成し、元のヘッドによって参照されるように設定されます(このオブジェクトは新しいヘッドになります)。

0

コードを再構成し、それ理解しやすく、コメントを追加しました:

/** 
*Insert a leaf node in a linked list 
*@param head represents the head node of the list. 
*@return the head node 
*/ 
public static Node insert(Node head,int data) { 

    //if head does not exist, create it and return it 
    if (head==null) { 
     return head=new Node(data); 
    } 

    else{//head exist 

     //search for the end of the linked list (leaf, has no next node) 
     Node current = head; 
     while(current.next!=null){ 
      current = current.next; 
     } 
     //at the end of loop the current.next == null (leaf) 
     //add new node as leaf 
     current.next = new Node(data); 
     return head; //return head unchanged 
    } 

} 

私はそれを明確にする手助けを願っています。