nowcoder-剑指offer-5-用两个栈实现队列

it2023-09-15  72

原题链接

原题要用两个栈实现队列,栈的特点是先进后出,队列的特点是先进先出 以下是代码,懒得写注释了,挺简单的

public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { while(!stack2.empty()){ stack1.push(stack2.pop()); } stack1.push(node); while(!stack1.empty()){ stack2.push(stack1.pop()); } } public int pop() { if(!stack2.empty()){ return stack2.pop(); } else { return 0; } } }
最新回复(0)