相同点:
栈和队列都属于线性表栈和队列插入操作都是限定在线性表的头尾进行栈和队列插入和删除的时间复杂度是O(1)不同点:
特性不同,栈先进后出 (LIFO,Last In First Out) ;队列先进先出 (FIFO,First In First Out)栈知识表的一端进行插入和删除操作,队列是在表的一端插入,另一端删除Java的栈(Stack)继承自 Vector,再往上的接口是 List/Collection;队列(Queue)直接继承自Collection接口栈实现队列:
/** * 两个栈组成队列 */ public class StackQueue<E> { //入队操作的栈 private Stack<E> stack1 =new Stack<>(); //出队操作的栈 private Stack<E> stack2 =new Stack<>(); /** * 压入队列元素,只使用stack1 * @param element */ public void push(E element) { stack1.add(element); } /** * 取出队列顶部元素 * @return */ public E poll() { // stack2的数据为空时,才把stack1中的元素压入stack2(两种情况:1、初始化时两个栈的数据均为空;2、stack2数据出栈出完了 if (stack2.isEmpty()) { while (stack1.size() > 0) { stack2.add(stack1.pop()); } } //stack1的数据出栈完成后,stack2仍然为空,说明两个栈的数据都为空 if (stack2.isEmpty()) { throw new RuntimeException("queue is Empty!"); } E head = stack2.pop(); return head; } }队列实现栈:
class MyStack { Queue<Integer> queue; /** Initialize your data structure here. */ public MyStack() { queue = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { queue.add(x); for (int i = 1; i < queue.size(); i++) { queue.add(queue.remove()); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return queue.poll(); } /** Get the top element. */ public int top() { return queue.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queue.size() == 0; } }栈和队列都属于线性表(linear list),而线性表是 n 个具有相同特性的数据元素的有限序列
