双端队列的实现

双端队列是由一些表组成的数据结构,具体简单实现代码如下(不是c++STL里面的哦~)

1.Push(X):将项X插入双端队列的前端。

2.Pop (  ): 从双端队列中删除前端项并将其返回。

3.Inject  (X) :将项X插入到双端队列的尾端。

4.Eject():从双端队列中删除尾端项并将其返回。

5.Empty () :双端队列是否为空。

6.IsFull () :双端队列是否满。

7.Show():打印双端队列中的元素。

 

 

 

typedef class Double_ended_queue Queue;
typedef int ElemType;
typedef class Double_ended_queue Queue_Node;
const ElemType MaxSize = 100;
class Double_ended_queue {
public:
	Double_ended_queue(int _f, int _l) :first(_f), last(_l), cur_f(_f), cur_l(_l) {};
	~Double_ended_queue() {};
public:
	void Push(ElemType X);
	ElemType& Pop();
	void Inject(ElemType X);
	ElemType& Eject();
	std::size_t Size()const;
	bool Empty()const;
	bool IsFull()const;
	void Show()const; 
private:
	int        first;
	int        last;
	int        cur_f;
	int        cur_l;
	ElemType   array[MaxSize];
};

void Double_ended_queue::Push(ElemType X) {
	if (cur_f == cur_l)
		throw std::out_of_range("Queue is Full!!");
	else {
		++cur_f;
		array[cur_f] = X;
	}
}

ElemType& Double_ended_queue::Pop() {
	if (cur_f == first)
		throw std::out_of_range("Queue is Empty!!");
	else {
		--cur_f;
		return array[cur_f];
	}
}

void Double_ended_queue::Inject(ElemType X) {
	if (cur_l == cur_f)
		throw std::out_of_range("Queue is Full");
	else {
		--cur_l;
		array[cur_l] = X;
	}
}

ElemType& Double_ended_queue::Eject() {
	if (cur_l == last)
		throw std::out_of_range("Queue is Empty!!");
	else {
		++cur_l;
		return array[cur_l - 1];
	}
}

bool Double_ended_queue::Empty()const {
	if (cur_f == first && cur_l == last)
		return true;
	else
		return false;
}

bool Double_ended_queue::IsFull()const {
	if (cur_f == last - 1 || cur_l == first + 1 || cur_f + cur_l == MaxSize - 1)
		return true;
	else
		return false;
}

void Double_ended_queue::Show()const {
	if (!Empty()) {
		for (int i = first + 1; i <= cur_f; ++i) {
			std::cout << array[i] << "\n";
		}
		for (int i = cur_l; i < last; ++i) {
			std::cout << array[i] << "\n";
		}
	}
	else
		throw std::out_of_range("Queue is Empty!!");
}

std::size_t Double_ended_queue::Size()const {
	return (cur_f - first) + (last - cur_l);
}

int main(void)
{
	int _first = -1;
	int _last = MaxSize;

	Queue queue(_first, _last);

	for (int i = 1; i < 3; ++i) {
		queue.Push(i);
	}

	for (int i = 4; i < 7; ++i) {
		queue.Inject(i);
	}

	queue.Show();
	std::cout <<"size:"<< queue.Size() << "\n";

	std::cout <<"Delete the elements of the front end is:"<<queue.Pop() << "\n";
	std::cout<<"The element at the end of the deletion is: "<<queue.Eject() << "\n";

	return 0;
}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值