https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
思路
两个栈A和B。栈A中的元素出栈并加入栈B,即可实现在B中的倒序。
appendTail:向栈A中加入一个元素
deleteHead:
if(B不为空) 弹出B栈顶元素
else(B为空A为空)返回-1
else(B为空A非空) 将A中元素依次加入B。然后弹出B的栈顶元素。
代码
class CQueue {
private Stack<Integer> a;
private Stack<Integer> b;
public CQueue() {
a=new Stack<Integer>();
b=new Stack<Integer>();
}
public void appendTail(int value) {
a.push(value);
}
public int deleteHead() {
if(!b.empty()){
return b.pop();
}
else if(a.empty()){
return -1;
}
else{
while(!a.empty())
b.push(a.pop());
return b.pop();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
结果
思考
看别人的题解,发现将Stack换成LinkedList耗时更短
class CQueue {
LinkedList<Integer> A, B;
public CQueue() {
A = new LinkedList<Integer>();
B = new LinkedList<Integer>();
}
public void appendTail(int value) {
A.addLast(value);
}
public int deleteHead() {
if(!B.isEmpty()) return B.removeLast();
if(A.isEmpty()) return -1;
while(!A.isEmpty())
B.addLast(A.removeLast());
return B.removeLast();
}
}
LinkedList 是一个双向链表。它也可以被当作堆栈、队列或双端队列进行操作。LinkedList随机访问效率低,但随机插入、随机删除效率低。