LinkedList 實現棧與佇列,比較簡單
阿新 • • 發佈:2019-01-23
import java.util.LinkedList;
public class LinkedListStackQueue {
public static void main(String[] args) {
LinkedListStackQueue linStackQueue=new LinkedListStackQueue();
// 棧的測試
linStackQueue.push(100);
linStackQueue.push(200);
linStackQueue.push(300);
linStackQueue.push(400 );
linStackQueue.pop();
System.out.println(linStackQueue.peek()); // 300
System.out.println(linStackQueue.isStackEmpty()); // false
// 佇列的測試
linStackQueue.put(100);
linStackQueue.put(200);
linStackQueue.put(300);
linStackQueue.put(400);
linStackQueue.get ();
System.out.println(linStackQueue.get()); // 200
System.out.println(linStackQueue.isQueueEmpty()); // false
}
private LinkedList linkList; // 棧
private LinkedList linkQueue;
public LinkedListStackQueue() {
// TODO Auto-generated constructor stub
linkList= new LinkedList();
linkQueue = new LinkedList();
}
public void push(Object o){ //壓棧
linkList.addFirst(o);
}
public Object pop(){ // 出棧
return linkList.removeFirst();
}
public Object peek(){ // 檢視棧頂元素
return linkList.peek();
}
public boolean isStackEmpty(){ // 檢視是否為空
return linkList.isEmpty();
}
public void put(Object o){ // 入隊
linkQueue.addLast(o);
}
public Object get (){ // 出隊
return linkQueue.removeFirst();
}
public boolean isQueueEmpty(){ // 檢視是否為空
return linkQueue.isEmpty();
}
}