注意:无论是栈还是队列,里面都会维护一个成员变量,该成员变量用于存储栈或队列中的元素,该成员变量 使用LinkedList类型。
package michael.wlq;
import java.util.LinkedList;
public class MyQueue {
/**
* 定义LinkedList类型的成员变量,往队列追加的元素存在此类型的变量中。
*/
private LinkedList<Object> list = new LinkedList<Object>();
/**
* 实现入队操作
*/
public void put(Object o) {
list.addLast(o);
}
/**
* 实现出队操作
*/
public Object get() {
return list.removeFirst();
}
/**
* 判断队列是否为空
*/
public boolean isEmpty() {
return list.isEmpty();
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.put("the first element");
myQueue.put("the secend element");
myQueue.put("the third element");
System.out.println(myQueue.get());
System.out.println(myQueue.get());
System.out.println(myQueue.get());
System.out.println(myQueue.isEmpty());
}
}
输出结果: