2016-08-10 1 views
2

// 나는 Node.java 클래스해당 개체 참조없이 개체가 업데이트되고 있습니까?

public class Node{ 

    int data; 
    Node next; 

    public Node(int d) { 
     data = d; 
    } 
} 

// 그리고 다른 자바 클래스

class LinkedList { 

    Node head; 

    public static void main(String[] args) { 
     LinkedList list = new LinkedList(); 
     //Executing this loop 
     for (int i = 0; i < 5; i++) { 

      **list.add(i);** 

     } 
    } 

    void add(int value){ 
     Node newNode = new Node(value); 

     if(head == null)//Very first time its create the head object when i = 0 
     { 
      head = newNode; 
     }else if(head.next == null){//This is for when i value is 1 
      head.next = newNode; 
     }else{ //else part execute i >= 2 
      //Created new node with head.next which mean value 1.And head is 0 
      Node temp = head.next; 
      // Just need this object initialization for reference 
      Node temp1 = newNode; 
      //Checking head.next is null or not if its null skip this loop execution 
      while(temp != null) 
      { 
       temp1 = temp; 
       temp = temp.next; 
      } 
      // Here we set newNode.next to null 
      newNode.next = temp1.next; 
      temp1.next = newNode; 
     } 
    } 
} 

내 질문은 여기에, 때 temp1.next이 = newNode; 라인 실행 헤드 오브젝트가 다음 값을 추가했습니다.

** // 예하다면 머리 = 0 head.next = 1 때 temp1.next = newNode; line 실행 head.next.next = 2가 head로 추가됩니다. 머리 객체 참조가 없을 때 어떻게 일어 났는가.

+0

잠시 시간을내어 질문을 올바르게 형식화하십시오. – azurefrog

+0

진지하게 : 당신이 우리를 도와주고 싶습니다. 그래서 당신은 당신의 질문을 적절히 포맷 할 시간을 보내십시오. 적절한 들여 쓰기, 서식 지정 등. 질문을 작성할 때 * 미리보기 *가 있습니다. – GhostCat

답변

1

헤드 개체를 업데이트하지 않습니다. head.next 개체를 업데이트하고 있습니다.

Node nextFromHead = head.next; // nextFromHead is 1 
Node nextFromNextFromHead = nextFromHead.next; // nextFromNextFromHead is 2 

head.next.nextnextFromNextFromHead 같은 목적이지만 (인 노드 2)에 대한 직접 연결되어 있지 않습니다

그래서

head.next.next 

는 다음과 같이 쓸 수있다 헤드 노드.

이것이 Java에서 참조가 작동하는 방식을 더 잘 이해하는 데 도움이 될 것이라고 생각합니다.

public class LinkedList { 

    static Node head; 

    public static void main(String[] args) { 

     LinkedList list = new LinkedList(); 
     for(int i = 0; i < 5; i++) 

      list.add(i); 

     Node currentNode = head; // in java we don't need object initialization for reference. Node temp1; would work just fine 

     System.out.println("==head node== " + currentNode); 
     while(currentNode.next != null) { 

      // here we increment 
      currentNode = currentNode.next; 

//   System.out.println("Last time we in here, next is null so print only current"); 
      System.out.println("==next node== " + currentNode); 
     } 
    } 

    void add(int value){ 
     Node newNode = new Node(value); 

     if(head == null)//Very first time its create the head object when i = 0 
     { 
      head = newNode; 
     }else if(head.next == null){//This is for when i value is 1 
      head.next = newNode; 
     }else{ //else part execute i >= 2 
      //Created new node with head.next which mean value 1.And head is 0 
      Node temp = head.next; 
      // Just need this object initialization for reference 
      Node temp1 = newNode; 
      //Checking head.next is null or not if its null skip this loop execution 
      while(temp != null) 
      { 
       temp1 = temp; 
       temp = temp.next; 
      } 
      // Here we set newNode.next to null 
      System.out.println(" ==temp1== " + temp1);// before 
      newNode.next = temp1.next; 
      temp1.next = newNode; 
      System.out.println(" ==temp1== " + temp1);// and after 
     } 

     System.out.println("==current node== " + head); 
     System.out.println(); 
    } 
} 

노드 클래스에는 개체를 제대로 볼 수있는 추가 toString()이 있습니다.

public class Node { 

    int data; 
    Node next; 

    public Node(int d) { 
     data = d; 
    } 

    @Override 
    public String toString() { 
     return "Node{" + 
       "data=" + data + 
       ", next=" + next + 
       '}'; 
    } 
} 
+0

확인. 하지만 여기서 혼란 스럽습니다. 예를 들어 MyClass에는 이름 필드가 있습니다. MyClass object1 = 새로운 MyClass(); object1.name = "object1"; MyClass object2 = object1; 이제 object2.name = "object2"; 이제는 object1.name을 출력하면이 예제에서 내 이해가 정확하고 Node 클래스에서 어떻게 발생하는지 "object1"이 아닌 "object2"가됩니다. – BoomirajP

+0

제 이해가 맞지 않으면 정정하십시오. Thanks – BoomirajP

+0

object1.name을 인쇄하면 "object2"가 인쇄됩니다. object1과 object2는 모두 같은 오브젝트를 참조하고 있습니다. – screab

0

"너는"머리 요소를 가지고있다.

코드를 살펴보십시오. LinkedList 클래스에는 필드 헤드가 있습니다. 그리고 당신이리스트의 add() 메소드를 호출 할 때마다; 해당 필드는 해당 메소드로 액세스 할 수 있습니다.

그래서,이 같은 작품에 추가 : 머리가 설정되지 않은

  1. 경우, 새가 머리가 설정되어있는 경우
  2. 만들었지 만이 아니는 "다음", 그 다음 노드입니다 만들고 머리에 연결
  3. 머리가 설정되어 있고 그의 "다음"다음 마지막으로 하나를 찾을 때까지 "다음"다음 검색 계속 ...; 다음 (아직)이없는 ...

그게 전부입니다. 또는 IT가 아닌 다른 예제를 사용해 볼 수도 있습니다.

일부 후크 및 짧은 로프를 가정하십시오. 당신은 "로프 목록"을 만들고 싶습니다.

  1. 목록이 없습니다. 당신은 첫 번째 로프를 가져다가 후크에 연결합니다.
  2. 첫 번째 로프, 당신 머리가 있습니다. 다른 밧줄을 추가합니다. 첫 번째 밧줄의 끝에 연결합니다 (아마도 옹이를 만듭니다).
  3. 다른 밧줄을 추가하면 ... 훅에서 시작하면 밧줄/옹이를 따라갈 수 있습니다. 느슨한 끝.

희망이 있습니다.

+0

예. 의견을 수락하십시오. 아직도 혼란 스러웠습니다. 네, 그 다음 요소가 없다는 것을 알았고 temp1.next = newNode;를 추가합니다. 머리 객체가 그 안에 새로운 요소를 얻는 방법은 다음과 같습니다. – BoomirajP

+0

당신이 무엇을 요구하고 있는지 잘 모르겠습니다. 나는 다른 예를 시도했다. 내 업데이트 된 답변을 참조하십시오. – GhostCat

관련 문제