一、环形队列
#include<iostream>
using namespace std;
//环形队列 queue push pop front back empty size
class Queue
{
public:
Queue(int size1=10)
:cap(size1)
,front(0)
,rear(0)
,size(0)
{
pQue = new int[cap];
}
~Queue()
{
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 (front == rear)
{
throw "queue is empty!";
}
front = (front + 1) % cap;
size--;
}
//获取队头元素
int front1()const
{
if (front == rear)
{
throw "queue is empty!";
}
return pQue[front];
}
//获取队尾元素
int rear1()const
{
if (front == rear)
{
throw "queue is empty!";
}
return pQue[(rear - 1 + cap) % cap];
}
//判断队空
bool empty()const
{
return front == rear;
}
//队列元素的个数
int size1()const
{
return size;// O(n)
//遍历一遍统计队列元素个数 O(n)
/*int size = 0;
for (int i = front; i != rear; i = (i + 1) % cap)
{
size++;
}
return size;*/
}
private:
//扩容接口
void expand(int size)
{
int* p = new int[size];
int i = 0;
int j = front;
for (; j != rear; i++, j=(j + 1) % cap)
{
p[i] = pQue[j];
}
delete[] pQue;
pQue = p;
cap = size;
front = 0;
rear = i;
}
private:
int* pQue; //存储地址
int cap; //容量
int front; //队头
int rear; //队尾
int size; //队元素数量
};
int main() {
int arr[] = { 12,4,56,7,89,31,53,75 };
Queue q;
for (int v : arr)
{
q.push(v);
}
cout << q.front1() << endl;
cout << q.rear1() << endl;
q.push(100);
q.push(200);
q.push(300);
q.push(400);
cout << q.front1() << endl;
cout << q.rear1() << endl;
while (!q.empty())
{
cout << q.front1() << " " << q.rear1() << endl;
q.pop();
}
return 0;
}
二、链式队列
#include<iostream>
using namespace std;
//链式队列
class LinkQueue
{
public:
LinkQueue()
{
head = new Node();
head->next = head;
head->pre = head;
}
~LinkQueue()
{
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* s = new Node(val);
s->next = head;
s->pre = head->pre;
head->pre->next = s;
head->pre = s;
}
//出队
void pop()
{
Node* p = head->next;
head->next = p->next;
p->next->pre = head;//
delete p;
}
//获取队头元素
int front()const
{
if (head->next == head)
{
throw "queue is empty!";
}
return head->next->data;
}
//获取队尾元素
int back()const
{
if (head->next == head)
{
throw "queue is empty!";
}
return head->pre->data;
}
//判空
int empty()const
{
return head->next == head;
}
//
private:
struct Node
{
Node(int data=0)
:data(data)
,next(nullptr)
,pre(nullptr)
{}
int data;
Node* next;
Node* pre;
};
Node* head;//指向头节点
};
int main() {
int arr[] = { 12,4,56,7,89,31,53,75 };
LinkQueue q;
for (int v : arr)
{
q.push(v);
}
cout << q.front() << endl;
cout << q.back() << endl;
q.push(100);
q.push(200);
q.push(300);
q.push(400);
cout << q.front() << endl;
cout << q.back() << endl;
while (!q.empty())
{
cout << q.front() << " " << q.back() << endl;
q.pop();
}
return 0;
}
总结
今天主要给大家实现了,队列的顺序结构和链式结构.