用两个栈来实现一个队列

mac2022-06-30  26

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。在牛客上做过这题。 //栈2入队列,栈1用来出队列

import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { if(stack1.empty()) while(!stack2.empty()) stack1.push(stack2.pop()); stack2.push(node); }

//必须要保证栈2顶部新进的元素压入栈1底部,这样出队列的时候新进的元素因为在底部,所以最后出队列。因此将栈2数据压入栈1时,需要判断栈1是否为空

// 其次,栈1为空是为了判断上一批排队的元素已全部出队列,避免栈2压进栈1的元素一直将栈1原先排队的元素压在底部

public int pop() { int n=-1; if(!stack1.empty()) { n=stack1.pop(); } if(stack1.empty()) while(!stack2.empty()) stack1.push(stack2.pop()); if(n==-1&&!stack1.empty()) n=stack1.pop(); return n; } }
最新回复(0)