使用LinkedList实现Stack与Queue
Stack:
代码实现:
public class MyStack { private LinkedList list = new LinkedList(); /** * 入栈 */ public void push(Object o) { list.addFirst(o); } /** * 出栈,删除 */ public Object pop() { return list.removeFirst(); } /** * 出栈,不删除 */ public Object peek() { return list.getFirst(); } public boolean isEmpty() { return list.isEmpty(); } public static void main(String[] args) { MyStack myStack = new MyStack(); myStack.push("one"); myStack.push("two"); myStack.push("three"); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println(myStack.isEmpty()); } }
编译运行:
Queue:
其具体实现:
public class MyQueue { private LinkedList list = new LinkedList(); /** * 从尾部插入 */ 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("one"); myQueue.put("two"); myQueue.put("three"); System.out.println(myQueue.get()); System.out.println(myQueue.get()); System.out.println(myQueue.get()); System.out.println(myQueue.isEmpty()); } }
编译运行: