代码随想录算法训练营第九天|Leetcode 232 用栈实现队列,Leetcode 225 用队列实现栈
栈和队列的基础
Leetcode 232.用栈实现队列
题目链接 232. 用栈实现队列
文章链接 https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html
视频链接 https://www.bilibili.com/video/BV1nY4y1w7VC
思路
先将元素押入到输入栈,要想弹出第一个进去的元素,则将输入栈的元素押入到另一个输出栈(要先判断此时输出栈是否为空),则此时的栈顶元素就是第一个被压入栈的元素(先进先出),可以进行弹出或返回实现pop(),top()操作
代码
class MyQueue {
public:
stack<int> input;
stack<int> output;
MyQueue() {
}
void push(int x) {
input.push(x);
}
int pop() {
if(output.empty()){//输出栈为空时将输入栈压入,如果输出栈不为空,则出队列时相当于跨过某些元素
while(!input.empty()){
output.push(input.top());//将栈顶元素压入栈底,实现后进后出
input.pop();
}
}
int top = output.top();
output.pop();
return top;
}
//和pop一样,之不过少了出栈操作,两种写法
int peek() {
if(output.empty()){
while(!input.empty()){
output.push(input.top());
input.pop();
}
}
int top = output.top();
return top;
}
//int peek(){
// int top = this->pop(); //调用已经实现的pop()函数获取栈顶元素
// output.push(top);//因为pop()把栈顶元素删除了,所以要压回来
// return top;
//}
bool empty() {
if(input.empty()&&output.empty()){
return true;
}
return false;
}
};
Leetcode 225.用队列实现栈
题目链接 225. 用队列实现栈
文章链接 https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html
视频链接 https://www.bilibili.com/video/BV1Fd4y1K7sm
deque容器讲解 C++ STL deque容器(详解版) (biancheng.net)
思路
这题我直接用deque容器做的,要实现后入先出的功能,对应队列的操作就是pop()时返回队尾元素,top()同理
题解:queue容器:定义一个队列即可,把队首元素不断插入到对尾,留下最开始队尾元素,实现pop()操作或者top()
代码
class MyStack {
public:
deque<int> q;
MyStack() {
}
void push(int x) {
q.push_back(x);
}
int pop() {
int top = q.back();
q.pop_back();
return top;
}
int top() {
return q.back();
}
bool empty() {
if(q.empty()){
return true;
}
return false;
}
};
- 题解
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
//将队首元素不断插入到对尾,直到队首元素为最开始队列的对尾
while(size!=1){
q.push(q.front());
q.pop();
size--;
}
int top = q.front();
q.pop();
return top;
}
int top() {
//调用已经实现的pop()元素,把弹出去的元素压回来
int top = this->pop();
q.push(top);
return top;
}
bool empty() {
if(q.empty()){
return true;
}
return false;
}
};

293

被折叠的 条评论
为什么被折叠?



