2012-10-29 4 views
-2

나는 연결된 목록과 관련된 숙제를 작업 중입니다. 우리는 큐 ADT를 구현해야하며, 문제가있는 한 가지 방법은 노드를 목록의 끝에 추가하는 것입니다 (큐 삽입 메서드). 여기 내 코드는 다음과 같습니다 사람이 정말 감사 것이 나를 도울 수 있다면자바에서 연결된 목록의 끝에 노드를 추가하십시오.

공용 클래스 대기열 QueueInterface {

private Node head; 
    private Node tail; 
    private int sz; 

    public Queue() { 
     head = null; 
     tail = null; 
     sz = 0; 
    } 

    public void enqueue(T newEntry) { 
     Node newElement = new Node(newEntry); 
     newElement.next = null; 
     tail.next = newElement; 
     tail = newElement; 
    } 

    public T dequeue() { 
     T result = null; 
     if(head != null) { 
      result = head.data; 
      head = head.next; 
      sz--; 
     } 
     return result; 
    } 

    public T getFront() { 
     return head.data; 
    } 

    public boolean isEmpty() { 
     if (head == null) { 
      return true; 
     } 
     return false; 
    } 

    public void clear() { 
     while (!isEmpty()) { 
      dequeue(); 
     } 
    } 

    @Override 
    public String toString() { 
     return "Queue [head=" + head + ", sz=" + sz + "]"; 
    } 

    public class Node { 

     private Node next; 
     private T data; 

     public Node (T newData) { 
      data = newData; 
     } 

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

    } 

} 

을 구현합니다. 시간 내 줘서 고마워! :)

+1

당신은'enqueue()'메소드를 가지고 있습니다. 현재 문제가 무엇입니까? 그리고 그것은 "작동하지 않습니다."보다 구체적으로 말하십시오. –

+0

그것은 java.lang.NullPointerException을 던지고있다. – salxander

+0

@ 잰더 - 네가 추가하는 * 첫 번째 것인지 확인하지 않기 때문에. 'tail'은 null입니다. 첫 번째 항목을 추가하는 경우를 처리해야합니다 (그런 다음'head'도 설정해야합니다) –

답변

1

목록이 비어있는 경우는 처리하지 않습니다. 첫 번째 항목을 추가하는 경우 tailnull이며 적절한 예외가 발생합니다.

사용하려고 시도하기 전에 null인지 확인하려면 tail을 확인하고 올바르게 작동해야합니다. head도 잊지 마세요.

1

이 줄은 필요 없으며 다음은 이미 null이어야합니다.

newElement.next = null; 

대기열에 넣은 다음에도 sm을 incremement하는 것을 잊었습니다.

빈 연결된 목록에 대기열에 추가하려고하면 어떻게됩니까? 이 경우를 처리해야합니다. NullPointerException

0

큐 삽입 방법이 tail.next에서 newElement으로 설정하려고 시도합니다. 꼬리가 아직 초기화되지 않은 경우 어떻게됩니까? NullPointerException이 발생합니다.

1
public void enqueue(T newEntry) { 
     Node newElement = new Node(newEntry); 
     newElement.next = null; 
     if(tail != null) 
     { 
     tail.next = newElement; 
     tail = newElement; 

     }else 
     { 
     head=tail=newElement; 
     } 
    } 

꼬리가 null인지 확인하십시오. tail가 null 경우는, 이것이 최초의 노드 인 것을 나타냅니다. 첫 번째 노드로 추가하십시오. 꼬리 뒤를 더한다.

관련 문제