JAVA-Eclipse
已知 Node class 設定如下,請使用它實作一個 Queue class 的 DeQueue 方法(從Queue 中移除一個Object),你實作的 Queue class 至少得包含變數宣告、Constructor(s)和DeQueue方法。並請再實作一支 Test Application 測試你設計的 DeQueue 方法。
public class Node{
Object obj;
Node next;
public Node(){
this(null);
}//constructor
public Node(Object obj){
this(obj, null);
}//constructor
public Node(Object obj, Node next){
this.obj = obj;
this.next = next;
}//constructor
public String toString(){
return obj.toString();
}//toString
}//node
1 個解答
- ΨετμουνΤLv 78 年前最佳解答
請參考我的做法
class Queue {
private Node front;
private Node rear;
Queue() {
front = null; rear = null;
}
void enQueue(Object o) {
Node node = new Node(o);
if(front == null) {
front = node;
rear = front;
}
else {
if(front.next == null) {
front.next = node;
}
rear.next = node;
rear = node;
}
}
Object peek() {
return front.obj;
}
Node deQueue() {
Node tmp = front;
if(tmp != null) {
front = tmp.next;
}
return tmp;
}
}
public class Y2041 {
public static void main(String[] args) {
Queue queue = new Queue();
queue.enQueue("A");
queue.enQueue("B");
queue.enQueue("C");
System.out.println(queue.peek());
queue.deQueue();
System.out.println(queue.peek());
}
}