循环队列
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 1000
typedef struct {
int *data;
int front, rear;//队头,队尾指针
}Sqnode,SqQueue;
//初始化队列
void InitQueue(SqQueue& Q)
{
Q.data = new int[MaxSize];
Q.front = Q.rear = 0;
}
//判断是否为空
bool EmptyQueue(SqQueue Q)
{
if (Q.front == Q.rear)
return true;
else
return false;
}
//入队
bool EnQueue(SqQueue& Q,int x)
{
if ((Q.rear + 1) % MaxSize == Q.front)
return false;
else
{
Q.data[Q.rear] = x;
Q.rear = ((Q.rear + 1) % MaxSize);
return true;
}
}
//出队
bool DeQueue(SqQueue& Q, int& x)
{
if(EmptyQueue(Q) )return false;
else {
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
}
//读取队头元素
bool GetQueue(SqQueue Q,int &x)
{
if (EmptyQueue(Q))return false;
else
{
x = Q.data[Q.front];
return true;
}
}
//获取队列元素个数
int GetSum(SqQueue Q)
{
return (Q.rear + MaxSize - Q.front) % MaxSize;
}
int main1()
{
SqQueue Q;
InitQueue(Q);
for (int i = 0; i < 10; i++)
{
EnQueue(Q, i + 1);
}
cout << "队列元素个数为:" << GetSum(Q) << endl;
cout << "打印队列" << endl;
for (int p = Q.front; p < Q.rear; p++)
{
cout << Q.data[p] << ' ';
}
cout << endl;
int x;
GetQueue(Q, x);
cout << "队头元素为: " << x << endl;
DeQueue(Q, x);
cout << "删除队头元素之后为:" << endl;
cout << "队列元素个数为:" << GetSum(Q) << endl;
for (int p = Q.front; p <Q.rear; p++)
{
cout << Q.data[p] << ' ';
}
cout << endl;
return 0;
}
链队列(有头节点)
//带头节点
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 1000
//队列节点
typedef struct LinkNode {
int data;
struct LinkNode *next;
};
//链式队列
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
//初始化
void InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.rear->next = NULL;
}
//判空
bool EmptyQueue(LinkQueue Q)
{
if (Q.front == NULL && Q.rear == NULL)
return true;
else return false;
}
//入队
bool EnQueue(LinkQueue& Q, int x)
{
LinkNode *p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = x;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return true;
}
//出队
bool DeQueue(LinkQueue& Q, int& x)
{
if (EmptyQueue (Q)) return false;
else {
LinkNode* p= Q.front->next;
x = p->data;
Q.front->next = p->next;
if (Q.rear == p)//原队列只有一个元素
{
Q.front = Q.rear;
}
free(p);
return true;
}
}
//获取长度
int GetSum(LinkQueue Q)
{
if (Q.front == Q.rear)
return 0;
else
{
int len = 0;
for (LinkNode* p = Q.front; p != Q.rear; p = p->next)
len++;
return len;
}
}
int main()
{
LinkQueue Q;
InitQueue(Q);
for (int j = 0; j < 10; j++)
{
EnQueue(Q, j + 1);
}
cout << "长度" << GetSum(Q)<<endl;
LinkNode* p = Q.front->next;
while(p!=NULL)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
int x;
DeQueue(Q, x);
cout << "队头元素为: " << x << endl;
cout << "删除队头元素" << endl;
p = Q.front->next;
while (p != NULL)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}