队列的特点:
先进后出,支持队头的元素访问,可以出队入队
分别使用数组和链表的方式实现了队列
//队列的特点:先进先出,后进后出
#include<iostream>
#include<time.h>
using namespace std;
class ArrQueue{
public:
ArrQueue(int size = 10)
:cap(size)
,front(0)
,rear(0)
{
pQue = new int[cap];
}
~ArrQueue(){
delete[]pQue;
pQue =nullptr;
}
public:
void push(int val){
if((rear+1)%cap==front){
expand(2*cap);
}
pQue[rear]=val;
rear=(rear+1)%cap;
size_++;
}
void pop(){
if(rear == front){
throw " ArrQueue is empty!";
}
front = (front+1)%cap;
size_--;
}
int top()const{
if(rear == front){
throw " ArrQueue is empty!";
}
return pQue[front];
}
int last()const{
if(rear == front){
throw " ArrQueue is empty!";
}
return pQue[(rear-1+cap)%cap];
}
bool isempty() const{
if(rear == front){
return true;
}
return false;
}
int ArrQueue_size() const{
//return size;
//或者遍历一遍统计队列元素个数O(n)
int size = 0;
for(int i =front;i!=rear;i=(i+1)%cap){
size++;
}
return size;
}
private:
int *pQue;
int cap;//空间容量
int front;//队头
int rear;//队尾
int size_;
private:
void expand(int size){
int *ptemp = new int[size];
int count = 0;
for(int i =front;i!=rear;i=(i+1)%cap){
ptemp[count++]=pQue[i];
}
delete []pQue;
pQue = ptemp;
front = 0;
rear = count;
cap = size;
}
};
class ListQueue{
public:
ListQueue(){
head = new Node();
head ->next = head;
head->pre = head;
}
~ListQueue(){
Node *p = head->next;
while(p!=head){
head->next = p->next;
p->next->pre = head;
delete p;
p = head->next;
}
delete head;
head = nullptr;
}
public:
void push(int val){
Node *p = new Node(val);
p->next = head;
p->pre = head->pre;
head->pre->next = p;
head->pre = p;
size_++;
}
void pop(){
Node *p = head->next;
head->next = p->next;
p->next->pre = head;
delete p;
size_--;
}
int front()const{
if(head->next==head){
throw"queue is empty!";
}
return head->next->data;
}
int back()const{
if(head->pre==head){
throw"queue is empty!";
}
return head->pre->data;
}
bool isempty(){
if(head->next==head){
return true;
}
return false;
}
private:
struct Node{
Node(int data = 0)
:data(data)
,next(nullptr)
,pre(nullptr)
{}//列表初始化
int data;
Node* next;
Node* pre;
};
Node* head;
int size_;
};
int main(){
ArrQueue myArrQueue;
ListQueue myListQueue;
srand(time(0));
for(int i=0;i<15;i++){
myArrQueue.push(rand()%100);
}
while(!myArrQueue.isempty()){
cout<<myArrQueue.top()<<endl;
myArrQueue.pop();
}
for(int i=0;i<15;i++){
myListQueue.push(rand()%100);
}
while(!myListQueue.isempty()){
cout<<myListQueue.front()<<endl;
myListQueue.pop();
}
}