题目:
方法一:
使用两个栈,进行push操作时,判断outstack是否空,如果非空,就把Outstack pop到Instack,然后再往instack里面push元素
class MyQueue {
Stack<Integer> Instack;
Stack<Integer> Outstack;
/** Initialize your data structure here. */
public MyQueue() {
Instack=new Stack<Integer>();
Outstack=new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!Outstack.empty()){
Instack.push(Outstack.pop());
}
Instack.push(x);
while(!Instack.empty()){
Outstack.push(Instack.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return Outstack.pop();
}
/** Get the front element. */
public int peek() {
return Outstack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(Outstack.empty()){
return true;
}else{
return false;
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
这种方法push时间复杂度为O(n),空间复杂度O(n)
其他方法O(1)
方法二:
再Instack里面,push方法:只要来一个元素,我就给你入栈,
但是pop方法:只有当Outstack是空,我才把Instack里面元素拿出来,不为空就不用管。(因为peek和pop都只是返回头元素,头元素不会因此改变,除非头被干掉)
push时间复杂度:O(1)空间O(n)
pop时间复杂度O(n)空间O(1)
因为pop方法会经历多次Instack倒入Outstack,平均之后还是O(n)
class MyQueue {
Stack<Integer> Instack;
Stack<Integer> Outstack;
Integer y;
/** Initialize your data structure here. */
public MyQueue() {
Instack=new Stack<Integer>();
Outstack=new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if(Instack.empty()){
y=x;
}
Instack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(Outstack.empty()){
while(!Instack.empty()){
Outstack.push(Instack.pop());
}
}
return Outstack.pop();
}
/** Get the front element. */
public int peek() {
if(!Outstack.empty()){
return Outstack.peek();
}
return y;
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(Outstack.empty()&&Instack.empty()){
return true;
}else{
return false;
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/