2.11 顺序队列

1️⃣1️⃣ 顺序队列

#include <iostream>
using namespace std;

class Queue{
private:
	int* queue;
	int front;
	int rear;
	int capacity;
public:
	Queue(int quequeCapacity=10);
	bool IsEmpty()const;
	int Front()const;
	int Rear()const;
	void Push(const int i);
	void Pop();
};

Queue::Queue(int queueCapacity):capacity(queueCapacity){
	queue = new int[capacity];
	front = rear = 0;
}

bool Queue::IsEmpty()const{
	return front == rear;
}



void Queue::Push(const int i){
	rear = (rear+1) % capacity; //用于判断新的rear是否到达capacity
	queue[rear] = i;
	if(front == (rear+1)%capacity){  //如果队列满了
		int *newQueue = new int [2*capacity];
		if(front < rear)
			copy(queue+front,queue+rear,newQueue);
		else {
			copy(queue+front,queue+capacity-1,newQueue);
			copy(queue,queue+rear,newQueue+capacity-front);
		}
		front = 0;
		rear = capacity - 1;
		capacity *= 2;
		delete []queue;
		queue = newQueue;
	}
}

void Queue::Pop(){
	front = (front+1) % capacity;  //用于判断新的front是否达到capacity
}

int Queue::Front()const{
	return queue[(front+1)%capacity];
}

int Queue::Rear()const{
	return queue[rear];
}



int main(){
	Queue q(4);
	q.Push(1);
	q.Push(2);
	cout << q.Front() << " " << q.Rear() << endl;
	q.Push(3);
	q.Push(4);
	cout << q.Front() << " " << q.Rear() << endl;
	q.Pop();
	cout << q.Front() << " " << q.Rear() << endl;
	q.Push(5);
	cout << q.Front() << " " << q.Rear() << endl;
	q.Push(6);
	cout << q.Front() << " " << q.Rear() << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值