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