字节面试这题没做出来,丢人
解题思路
想象有两个装乒乓球的盒子,要取出最下面那个就只能把所有的倒到另一个空盒子里
本题同解
C++代码
class CQueue {
private:
stack<int> sa;
stack<int> sb;
public:
CQueue() {
}
void appendTail(int value) {
sa.push(value);
}
int deleteHead() {
if (sa.empty()) return -1;
while (!sa.empty()) {
sb.push(sa.top());
sa.pop();
}
int ans = sb.top();
sb.pop();
while (!sb.empty()) {
sa.push(sb.top());
sb.pop();
}
return ans;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
Java代码
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(new Integer(value));
}
public int deleteHead() {
if (st1.isEmpty()) return -1;
while (!st1.isEmpty()) {
st2.push(st1.pop());
}
int ans = st2.pop();
while (!st2.isEmpty()) {
st1.push(st2.pop());
}
return ans;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/