手写STL中的deque双端队列
程序员文章站
2022-05-23 23:14:25
...
自己写了类实现了deque的功能,还行吧!
用了函数模板了。
STL中dpque的函数↓:
完整代码:
#include<iostream>
using namespace std;
const int MaxSize = 60;//队列容量
template <typename T>
class Deque {
private:
T data[MaxSize];
int front, rear, count;
public:
Deque() {
this->front = 0;
this->rear = 0;
this->count = 0;
}
bool push_front(T x)
{
if ((rear + 1) % MaxSize == front) return false;
data[front] = x;//元素e进队
front = (front - 1 + MaxSize) % MaxSize;
count++;
return true;
}
bool push_back(T x)
{
if (count == MaxSize) return false;
else {
rear = (rear + 1) % MaxSize;
data[rear] = x;
count++;
return true;
}//else
}
T pop_front()
{
if (count == 0) return 1;
else {
front = (front + 1) % MaxSize;
count--;
return data[front];
}//else
}
T pop_back()
{
if (count == 0) return -1;
T x;
x = data[rear];//提取队尾元素
rear = (rear - 1 + MaxSize) % MaxSize;
count--;
return x;
}
};
int main()
{
Deque<int> q;
q.push_front(2);
cout << q.pop_back() << endl;
q.push_front(3);
q.push_back(4);
cout << q.pop_front() << endl;
return 0;
}
上一篇: 数据结构实验之栈与队列十一:refresh的停车场
下一篇: 栈的创建及其操作