2014-11-29 2 views
1

이것은 링크 된 목록 (기본이 아닌)에 대한 코드입니다. "addLast"메서드는 다음과 같은 오류가 발생하고 해결 방법을 모르겠습니다. "정적이 아닌 변수는 정적 컨텍스트에서 참조 할 수 없습니다." 다음 행에 대해 이야기하고 있습니다. return new Node (x, null); 이 문제를 해결하는 방법에 대한 도움을 주시면 감사하겠습니다.링크 된 목록의 끝에 노드 추가 (java)

Node 정적 중첩 클래스 확인 :

private static class Node { ... } 

를 또는, addLast 방법을 인스턴스 메서드합니다

public Node addLast(Node header, int x) { ... } 

답변

0

제거를 여기

public class LinkedList 
{ 

    private class Node 
    { 
     int item; 
     Node link; 

     public Node() 
     { 
      item = Integer.MIN_VALUE; 
      link = null; 

     } 

     public Node (int x, Node p) 

     { 
      item = x; 
      link = p; 

     } 

    } //End of node class 


    private Node head; 


    public LinkedList() 
    { 
     head = null; 
    } 

    //adds a node to the start of the list with the specified data 
    //added node will be the first node in the list 

    public void addToStart(int x) 
    { 
     head = new Node(x, head); 
    } 


    //adds a number at end of list 
    public static Node addLast(Node header, int x) 
    { 
     // save the reference to the header so we can return it. 
     Node ret = header; 

     // check base case, header is null. 
     if (header == null) { 
      return new Node(x, null); 
     } 

     // loop until we find the end of the list 
     while ((header.link != null)) { 
      header = header.link; 
     } 

     // set the new node to the Object x, next will be null. 
     header.link = new Node(x, null); 
     return ret; 
    } 


    //displays the list 
    public void printList() 
    { 
     Node position = head; 
     while(position != null) 
     { 
      System.out.print(position.item + " "); 
      position = position.link; 
     } 

     System.out.println(); 
    } 
} 
+0

addLast가 내 메인에 액세스하려면 정적이어야하므로 내가 할 수 없습니다. –

+0

아니요, main에'addLast'를 호출하는'LinkedList'가 필요합니다 -'list = new LinkedList(); list.addLast (5); list.addLast (6);'... –

+0

for 루프를 설명해 주시겠습니까? –

1

당신에게 두 가지 솔루션을하는 감사의 static 한정자- 끝까지 추가 할 목록이 있어야 정적이 아니어야합니다. Node은 개인 중첩 클래스이기 때문에이 클래스 외부의 코드는 Node이 무엇인지 알지 못하므로 (또는 신경 써서) 전달할 수 없으므로 Node을 가져 가거나 돌려 보내서는 안됩니다.

public void addLast(int x) { 
    if (head == null) head = new Node(x, null); 
    else { 
     Node p = head; 
     while (p.link != null) p = p.link; 
     p.link = new Node(x, null); } } 
+0

정적 중첩 클래스는 * 필요하지 않습니다. 그렇다고해서 그렇게 중첩 될 수는 없습니다. 그것을 정적이 아닌 것으로 만드는 것은 OP 문제와 무관합니다. –

+0

@ChrisDodd 사실, 꼭 필요한 것은 아니지만,'Node'가'LinkedList'와는 독립적이게 더 논리적 인 것처럼 보입니다. – August

+0

목록으로 무엇을하고 싶은가에 따라 다릅니다. 비 정적으로 만들면 노드가 포함 된 목록의 머리를 다시 참조 할 수 있습니다. 이는 일부 알고리즘에 유용 할 수 있습니다. –

0

대답은 에러 라인이다

비 정적 변수 정적 콘텍스트

제거 방법 addLast 대한 static에서 참조 될 수 없다.

public Node addLast(Node header, int x) 
{ 
    .... 
} 
관련 문제