用两个栈实现队列(简单)
2020年8月11日
题目来源:力扣
解题
- 暴力
每次传数就传到st1,要删除值就把st1的值传到st2,这样就会反转数值,把最先进栈的放到最上面,可以输出,做删除操作后再把st2传回st1。这样太费时了
class CQueue {
private Stack<Integer> st1;
private Stack<Integer> st2;
public CQueue() {
st1=new Stack<Integer>();
st2=new Stack<Integer>();
}
public void appendTail(int value) {
st1.push(value);
}
public int deleteHead() {
int delnum=-1;
if(!st1.empty()){
while(!st1.empty()){
st2.push(st1.pop());
}
delnum=st2.pop();
while(!st2.empty()){
st1.push(st2.pop());
}
}
return delnum;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
- 暴力plus
专门把st2作为输出专用,当st2为空的时候再把st1的所有数出栈压进去,否则就直接用st2里的值
class CQueue {
private Stack<Integer> st1;
private Stack<Integer> st2;
public CQueue() {
st1=new Stack<Integer>();
st2=new Stack<Integer>();
}
public void appendTail(int value) {
st1.push(value);
}
public int deleteHead() {
int delnum=-1;
//当st2为空,就把st1出栈放进去
if(st2.empty()){
while(!st1.empty()){
st2.push(st1.pop());
}
}
if(!st2.empty()){
delnum=st2.pop();
}
return delnum;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/