题目:232.用栈实现队列
尝试解答:之前做过,在逻辑上没有太大的问题,此次刷题要更注重代码语言。自己还写不出代码,需要看题解。
两个栈来模拟,一个进栈,一个出栈。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
//这个函数是干啥用的?
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
//如果stOut里面存有数据,那么队列最开头的元素就是stOut.top()
}
int peek() {
if(!stOut.empty()){
return stOut.top();
}else{
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
return stOut.top();
}
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
题目:225.用队列实现栈
这道题不想上面的题,之前做完印象已经不深了。
尝试解答写下如下代码,在pop和top有问题。
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int count = que.size() - 1;
for(int i = 1; i <= count; i++){
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
int top() {
// int count = que.size() - 1;
// for(int i = 1; i <= count; i++){ //此处计数循环出错,i应该从1开始
// que.push(que.front());
// que.pop();
// }
// int result = que.front();
// return result;
return que.back();
}
bool empty() {
return que.empty();
}
};