As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Example
For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2
Challenge
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE
用两个stack来实现queue 第一个stack正向装入数字 然后pop出来 push到第二个stack中
每次判定stack2是否为empty(这样做可以防止后来加入的数字push到stack2中 这样顺序就乱了 所以要等stack2 是空的时候才再次网stack2里面push数字) 如果为empty继续push入stack1 pop出来的数
public class Solution { private Stack<Integer> stack1; private Stack<Integer> stack2; public Solution() { stack1 = new Stack<Integer>(); stack2 = new Stack<Integer>(); } public void push(int element) { stack1.push(element); } public int pop() { if (stack2.empty()) { while (!stack1.empty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } public int top() { if (stack2.empty()) { while (!stack1.empty()) { stack2.push(stack1.pop()); } } return stack2.peek(); } }
没有评论:
发表评论