欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

手写STL中的deque双端队列

程序员文章站 2022-05-23 23:14:25
...

自己写了类实现了deque的功能,还行吧!
用了函数模板了。

STL中dpque的函数↓:
手写STL中的deque双端队列
完整代码:

#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;
}

相关标签: 栈与队列