LeetCode232.用栈实现队列
文章链接:代码随想录
题目链接:232.用栈实现队列
思路:熟悉栈和队列的基本操作,明白互相实现的原理就可以,很简单
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if (stOut.empty()){
while (!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int res = stOut.top();
stOut.pop();
return res;
}
int peek() {
int res = this -> pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
private:
stack<int> stIn;
stack<int> stOut;
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
LeetCode225. 用队列实现栈
文章链接:代码随想录
题目链接:225. 用队列实现栈
思路:用一个队列即可实现,两个队列另一个也是备用,反而操作麻烦一些。
两个队列实现:
class MyStack {
public:
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size() - 1;
while (size--){
que1.push(que.front());
que.pop();
}
int res = que.front();
que.pop();
while (!que1.empty()){
que.push(que1.front());
que1.pop();
}
return res;
}
int top() {
int res = this -> pop();
que.push(res);
return res;
}
bool empty() {
return que.empty();
}
private:
queue<int> que;
queue<int> que1;
};
/**
* 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:
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size() - 1;
while (size--){
que.push(que.front());
que.pop();
}
int res = que.front();
que.pop();
return res;
}
int top() {
int res = this -> pop();
que.push(res);
return res;
}
bool empty() {
return que.empty();
}
private:
queue<int> que;
};
/**
* 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();
*/
今天题目很简单,主要是对stack和queue容器适配器的概念加深了理解,另外这段刚好在听侯捷的STL的课,对C++标准库的版本和编译器的了解更全面了:我们现在所使用的是SGI版本的STL,适配Linux下的g++编译器。
另外今天做题遇到了this指针的操作,看了几篇文章,大致就是this可以在成员函数内部调用,指向这个对象本身,可以调用这个对象的数据或函数。this涉及的知识和操作很多,以后再深入学习。
第十天打卡,这几天配合着刷题和看侯捷老师STL的课,感觉对C++和STL的理解清晰了很多,加油!!!