用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

来源:互联网 发布:不用网络的单机游戏 编辑:程序博客网 时间:2024/06/07 10:29
import java.util.Stack;public class Solution {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();            public void push(int node) {    stack1.push(node);    }        public int pop() {    int res=0;    if(!stack2.isEmpty()){    res=stack2.pop();    }else {    while(!stack1.isEmpty()){    stack2.push(stack1.pop());    }    if(!stack2.isEmpty()){    res=stack2.pop();    }    }    return res;        }}

思路:栈1作为入队的一端,栈2作为出队的一端,入队是即是压入栈1,出队时从栈2出,这时应该先判断栈2是否为空,如果为空,栈1的全部弹出然后压入栈2,然后再栈2弹出

阅读全文
0 0