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();
}
}
感謝您的意見。 – 2015-02-10 03:02:16