彦祖天天见
栈(Stack)和队列(Queue)是两种常见的数据结构,它们都是线性数据结构,但在元素的插入和删除方式上有所不同。
栈(Stack):
- 栈是一种后进先出(Last-In-First-Out,LIFO)的数据结构。
- 元素的插入和删除操作只能在栈的顶部进行。
- 插入操作称为入栈(Push),删除操作称为出栈(Pop)。
- 栈的顶部元素是最后一个插入的元素,也是唯一可以访问的元素。
- 栈的应用包括函数调用、表达式求值、括号匹配等。
队列(Queue):
- 队列是一种先进先出(First-In-First-Out,FIFO)的数据结构。
- 元素的插入操作只能在队列的尾部进行,删除操作只能在队列的头部进行。
- 插入操作称为入队(Enqueue),删除操作称为出队(Dequeue)。
- 队列的头部元素是最先插入的元素,也是唯一可以访问的元素。
- 队列的应用包括任务调度、缓冲区管理、广度优先搜索等。
在C++中,可以使用标准库中的std::stack
和std::queue
来实现栈和队列。这些容器提供了相应的成员函数和操作符来进行元素的插入、删除和访问操作。
#include <iostream>
#include <stack>
#include <queue>
int main() {
// 使用 std::stack 实现栈
std::stack<int> myStack;
// 入栈操作
myStack.push(10);
myStack.push(20);
myStack.push(30);
// 出栈操作
while (!myStack.empty()) {
int topElement = myStack.top();
std::cout << "Top element: " << topElement << std::endl;
myStack.pop();
}
// 使用 std::queue 实现队列
std::queue<int> myQueue;
// 入队操作
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
// 出队操作
while (!myQueue.empty()) {
int frontElement = myQueue.front();
std::cout << "Front element: " << frontElement << std::endl;
myQueue.pop();
}
return 0;
}
今天学习两道题目加深栈和队列的印象
class MyQueue {
public:
stack<int> In;
stack<int> Out;
MyQueue() {
}
void push(int x) {
In.push(x);
}
int pop() {
if(Out.empty()){
while(!In.empty()){
Out.push(In.top());
In.pop();
}
}
int res=Out.top();
Out.pop();
return res;
}
int peek() {
int res = this->pop();
Out.push(res);
return res;
}
bool empty() {
return In.empty()&&Out.empty();
}
};
class MyStack {
public:
queue<int> one;
queue<int> two;
MyStack() {
}
void push(int x) {
one.push(x);
}
int pop() {
int size=one.size();
size--;
while(size--){
two.push(one.front());
one.pop();
}
int res = one.front();
one.pop();
one = two;
while(!two.empty()){
two.pop();
}
return res;
}
int top() {
return one.back();
}
bool empty() {
return one.empty();
}
};