2015-02-10 115 views
0

我做了一個泛型類型的隊列。當我嘗試打印出我創建的兩個隊列的內容時,結果以最後一個元素的格式返回,即第一個元素輸出(LIFO)而不是先進先出(FIFO)。我似乎無法按照正確的順序打印(FIFO)。我使用三個不同的類。該MYNODE類:隊列打印查詢

public class MyNode<T> { 
    public T payload; 
    public MyNode<T> next; 
    public MyNode<T> previous; 

    public MyNode(T payload) { 
     this.payload = payload; 
    } 
    public MyNode(T payload, MyNode<T> next, MyNode<T> previous) { 
     this.payload = payload; 
     this.next = next; 
     this.previous = previous; 
    } 

    public T getPayload() { 
     return payload; 
    } 

    public MyNode<T> getNext() { 
     return next; 
    } 

    public MyNode<T> getPrevious() { 
     return previous; 
    } 

    public void setPayload(T payload) { 
     this.payload = payload; 
    } 

    public void setNext(MyNode<T> next) { 
     this.next = next; 
    } 

    public void setPrevious(MyNode<T> previous) { 
     this.previous = previous; 
    } 
} 

的TestQueue類:

public class TestQueue { 
    public static void main(String[] args) { 
     MyQueue<String> qStr = new MyQueue<String>(); 
     MyQueue<Integer> qInt = new MyQueue<Integer>(); 

     qStr.enqueue("hello"); 
     qStr.enqueue("world"); 
     System.out.println("Size of queue: " + qStr.size()); 
     System.out.println(qStr); 
     System.out.println(); 

     qInt.enqueue(42); 
     qInt.enqueue(3); 
     System.out.println("Size of queue: " + qInt.size()); 
     System.out.println(qInt); 
     System.out.println(); 

     qStr.dequeue(); 
     System.out.println(qStr); 
     System.out.println(); 

     qInt.dequeue(); 
     System.out.println(qInt); 
    } 
} 

的myQueue中類:

public class MyQueue<T> { 
    public int size = 0; 
    public MyNode<T> front = new MyNode<T>(null); 
    public MyNode<T> back = new MyNode<T>(null); 

    public void enqueue(T payload) { 
     MyNode<T> newNode = new MyNode<T>(payload); 
     newNode.next = front; 
     front = newNode; 
     if (isEmpty()) { 
      back = newNode; 
     } 
     size++; 
    } 

    public T dequeue() { 
     if (isEmpty()) { 
      return null; 
     } 
     T payload = front.payload; 
     front = front.getNext(); 
     size--; 
     return payload; 
    } 

    public boolean isEmpty() { 
     return front == null; 
    } 

    public int size() { 
     return size; 
    } 

    public String toString() { 
     return front.getPayload().toString(); 
    } 
} 

回答

0

你在隊列的前面插入,而不是後面的新人。問題是:

newNode.next = front; 
//back.next = null; 
front = newNode; 

你應該做的是:

Node tmp = front; 
while (tmp.next != null) tmp = tmp.next; 
tmp.next = newNode; 

我離開前一場和大小的更新給你。

+0

感謝您的意見。 – 2015-02-10 03:02:16