232. 用栈实现队列
题目链接
思路
记得是用两个栈实现的队列,但是细节记不太住,看了视频才勉强缝缝补补做出来。
本人题解
class MyQueue {
public:
stack<int> stackIn;
stack<int> stackOut;
MyQueue() {
//初始化队列,就是初始化栈
//stack stackIn;
//stack stackOut;错误!!!
}
void push(int x) {
stackIn.push(x);
}
int pop() {
int res;
if (stackOut.empty()) {
//因为每次都是全部导入,因此只能在
//stackOut为空才导入,否则数据顺序错乱
while (!stackIn.empty()) { //每次全部导入!
stackOut.push(stackIn.top());
stackIn.pop();
}
}
res = stackOut.top();
stackOut.pop();
return res;
}
int peek() {
int result;
result = this->pop();
stackOut.push(result);
return result;
}
bool empty() {
if (stackIn.empty() && stackOut.empty()) return true;
return false;
}
};
225. 用队列实现栈
题目链接
思路
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
本人题解(运行成功,提交超出时间限制)
class MyStack {
public:
queue<int> myQue;
int count = 0;//记住队列的个数
MyStack() {
}
void push(int x) {
myQue.push(x);
count++;//记录个数
}
int pop() {
int n = count - 1;
while (n--) {
myQue.push(myQue.front());//因为push时count会++
myQue.pop();
count--;//此时count--与上面的++抵消,总个数是不变的
}
int res = myQue.front();//注意,这里是front不是top
myQue.pop();
count--;
return res;
}
int top() {
//int result = this->pop();
//myQue.push(result);
//这两行代码是我参考(脑子里参考而已)用两个栈模拟队列的
//其实是错的,因为直接调用this->pop的时候队列里的元素已经减少了1个。
int m = count - 1;
while (m--) {
myQue.push(myQue.front());
myQue.pop();
count--;
}
int result = myQue.front();
return result;
}
bool empty() {
return myQue.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
修改后题解
class MyStack {
public:
queue<int> myQue;
//int count = 0;//记住队列的个数
MyStack() {
}
void push(int x) {
myQue.push(x);
//count++;//记录个数
}
int pop() {
int n = myQue.size() - 1;
while (n--) {
myQue.push(myQue.front());//因为push时count会++
myQue.pop();
//count--;//此时count--与上面的++抵消,总个数是不变的
}
int res = myQue.front();//注意,这里是front不是top
myQue.pop();
//count--;
return res;
}
int top() {
int result = myQue.back();
return result;
}
bool empty() {
return myQue.empty();
}
};