目录
第4章:queue容器
4.1 queue容器简介
queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口,queue容器允许从一端新增元素,从另一端移除元素。
queue所有元素的进出都必须符合”先进先出”的条件,只有queue的顶端元素,才有机会被外界取用。queue不提供遍历功能,也不提供迭代器。
4.2 queue构造函数
queue<T> queT; //queue采用模板类实现,queue对象的默认构造形式:
queue(const queue &que); //拷贝构造函数
4.3 queue存取、插入和删除操作
push(elem); //往队尾添加元素
pop(); //从队头移除第一个元素
back(); //返回最后一个元素
front(); //返回第一个元素
4.4 queue赋值操作
queue& operator=(const queue &que); //重载等号操作符
4.5 queue大小操作
empty(); //判断队列是否为空
size(); //返回队列的大小
4.6 示例
#include<iostream>
#include<queue>
using namespace std;
class Person {
public:
Person(string name, int math, int english) {
this->m_Name = name;
this->m_math = math;
this->m_english = english;
}
string m_Name;
int m_math;
int m_english;
};
void test() {
queue<Person> q;
//准备数据
Person p1("学生1", 80,90);
Person p2("学生2", 85,85);
Person p3("学生3", 90,95);
Person p4("学生4", 80,100);
//入队
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
cout << "队列大小为:" << q.size() << endl;
while (!q.empty()) {
//查看队头
cout << "队头元素:" << q.front().m_Name << "-" << "math:" << q.front().m_math << " " << "english:" << q.front().m_english << endl ;
//查看队尾
cout << "队尾元素:" << q.back().m_Name << "-" << "math:" << q.back().m_math << " " << "english:" << q.back().m_english << endl << endl;
//出队
q.pop();
}
cout << "队列大小为:" << q.size() << endl;
}
int main() {
test();
return 0;
}
4.7 数据结构案例 - LeetCode225
题目:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
注意:
- 你只能使用队列的基本操作 —— 也就是
push to back
、peek/pop from front
、size
和is empty
这些操作。 - 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
题解:
使用一个队列实现栈的操作。
(1)使用一个队列时,为了满足栈的特性,即最后入栈的元素最先出栈,同样需要满足队列前端的元素是最后入栈的元素。
(2)入栈操作时,首先获得入栈前的元素个数 n,然后将元素入队到队列,再将队列中的前 n 个元素(即除了新入栈的元素之外的全部元素)依次出队并入队到队列,此时队列的前端的元素即为新入栈的元素,且队列的前端和后端分别对应栈顶和栈底。
(3)由于每次入栈操作都确保队列的前端元素为栈顶元素,因此出栈操作和获得栈顶元素操作都可以简单实现。出栈操作只需要移除队列的前端元素并返回即可,获得栈顶元素操作只需要获得队列的前端元素并返回即可(不移除元素)。
(4)由于队列用于存储栈内的元素,判断栈是否为空时,只需要判断队列是否为空即可。
#include<iostream>
#include<queue>
using namespace std;
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
int n = q.size();
q.push(x);
for (int i = 0; i < n; i++) {
q.push(q.front());
q.pop();
}
}
int pop() {
int r = q.front();
q.pop();
return r;
}
int top() {
int r = q.front();
return r;
}
bool empty() {
return q.empty();
}
};
void Print(MyStack& v)
{
if(!v.empty())
{
cout << v.pop() << " ";
}
cout << endl;
}
int main()
{
MyStack st; //定义一个字符顺序栈st
cout << "建立空栈st\n";
cout << "栈st" << (st.empty() ? "空" : "不空") << endl;
cout << "1进栈\n"; st.push(1);
cout << "2进栈\n"; st.push(2);
cout << "3进栈\n"; st.push(3);
cout << "4进栈\n"; st.push(4);
cout << "5进栈\n"; st.push(5);
while(!st.empty())
{
cout << st.pop() << " "<<endl;
};
cout << "栈st:" << (st.empty() ? "空" : "不空") << endl;
return 0;
}