循环队列
#include <iostream>
using namespace std;
#define MAXQSIZE 100
typedef int QElemType;
typedef struct
{
QElemType* base;
int front; //头指针
int rear; //尾指针
}SqQueue;
//初始化一个空队列
int InitQueue(SqQueue& Q)
{
Q.base = new QElemType[MAXQSIZE];
if (!Q.base) return 0;
Q.front = Q.rear = 0;
return 1;
}
int QueueLength(SqQueue Q)
{
return(Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
//入队
int EnQueue(SqQueue& Q, QElemType e)
{
//rear移动+1取余等于front则队满
if ((Q.rear + 1) % MAXQSIZE == Q.front)
return 0;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE; //队尾指针加1/地址循环
}
//出队--删除队头元素,用e返回其值
int DeQueue(SqQueue& Q, QElemType& e)
{
if (Q.front == Q.rear) return 0; //队空
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE; //对头指针+1
return 1;
}
QElemType GetHead(SqQueue Q)
{
if (Q.front != Q.rear)
return Q.base[Q.front];
}
int main()
{
SqQueue Q;
QElemType e;
InitQueue(Q);
int n;
cout << "请输入入队个数: ";
cin >> n;
cout << "请依次输入入队的数据: " << endl;
for (int i = 0; i < n; i++)
{
cin >> e;
EnQueue(Q, e);
}
cout << "GetHead: ";
cout << GetHead(Q) << endl;
cout << "出队: " << endl;
for (int i = 0; i < n; i++)
{
DeQueue(Q, e);
cout << e << endl;
}
return 0;
}
链队
#include <iostream>
using namespace std;
#define MAXQSIZE 100
typedef int QElemType;
typedef struct QNode
{
QElemType data;
struct QNode* next;
}QNode, * QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = new QNode; //生成新结点作为头结点,队头和队尾指针指向此结点
Q.front->next = NULL; //头结点指针域为空
return 1;
}
//入队--插入元素e到队尾
int EnQueue(LinkQueue& Q, QElemType e)
{
QueuePtr p = new QNode;
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return 1;
}
//出队--删除队头元素,用e返回值
int DeQueue(LinkQueue& Q, QElemType& e)
{
if (Q.front == Q.rear)return 0;
QueuePtr p = Q.front->next; //p指向队头元素
e = p->data; //e保存队头元素值
//头结点指向的前一个指向p队头的next,断掉原队头
Q.front->next = p->next; //修改头结点指针域
if (Q.rear == p)Q.rear = Q.front; //如果最后一个元素被删除,队尾指针指向头结点
delete p;
return 1;
}
QElemType GetHead(LinkQueue Q)
{
if (Q.front != Q.rear)
return Q.front->next->data;
return 0;
}
int main()
{
LinkQueue Q;
QElemType e;
InitQueue(Q);
int n;
cout << "请输入入队个数: ";
cin >> n;
cout << "请依次输入入队的数据: " << endl;
for (int i = 0; i < n; i++)
{
cin >> e;
EnQueue(Q, e);
}
cout << "GetHead: ";
cout << GetHead(Q) << endl;
cout << "出队: " << endl;
for (int i = 0; i < n; i++)
{
DeQueue(Q, e);
cout << e << endl;
}
return 0;
}