详细说明:https://blog.csdn.net/qq_43643944/article/details/115306135
1、顺序队列
#include <iostream>
using namespace std;
typedef int ElemType;
const int MAXSIZE = 10;
struct SqQueue {
ElemType data[MAXSIZE];
int front, rear;//队首指针、队尾指针
};
void InitSqQueue(SqQueue &Q) {//初始化
Q.front = Q.rear = 0;
}
int SqQueueLength(SqQueue Q) {//求队列长度
int length = (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
return length;
}
bool EnQueue(SqQueue &Q, ElemType val) {//入队
if ((Q.rear + 1) % MAXSIZE == Q.front)
return false;
else {
Q.data[Q.rear] = val;
Q.rear = (Q.rear + 1) % MAXSIZE;
return true;
}
}
bool DeQueue(SqQueue &Q, ElemType &e) {//出队
if (Q.front == Q.rear)
return false;
else {
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
return true;
}
}
int main() {
SqQueue Q;
InitSqQueue(Q);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
cout << "遍历队列:";
for (int i = Q.front; i != Q.rear; i = (i + 1) % MAXSIZE) {
cout << Q.data[i] << " ";
}
cout << endl;
cout << "队列长度为:" << SqQueueLength(Q) << endl;
int e;
DeQueue(Q, e);
cout << "删除元素" << e << ":";
for (int i = Q.front; i != Q.rear; i = (i + 1) % MAXSIZE) {
cout << Q.data[i] << " ";
}
cout << endl;
cout << "队列长度为:" << SqQueueLength(Q) << endl;
return 0;
}
2、链队
#include <iostream>
using namespace std;
typedef int ElemType;
struct LNode {
ElemType data;
struct LNode *Next;
};
struct LinkQueue {
LNode *front, *rear;//队首指针、队尾指针
int count;//统计个数
};
bool InitSqQueue(LinkQueue &Q) {//初始化
LNode *p = (LNode *) malloc(sizeof(LNode));
if (p == NULL)
return false;
p->Next = NULL;
Q.rear = Q.front = p;
Q.count = 0;
return true;
}
bool EnQueue(LinkQueue &Q, ElemType val) {//入队
LNode *p = (LNode *) malloc(sizeof(LNode));
if (p == NULL)
return false;
p->data = val;
p->Next = NULL;
Q.rear->Next = p;
Q.rear = p;
Q.count++;
return true;
}
bool DeQueue(LinkQueue &Q, ElemType &e) {//出队
if (Q.front == Q.rear)
return false;
LNode *q = Q.front->Next;
e = q->data;
Q.front->Next = q->Next;
if (q->Next == NULL) {
Q.rear = Q.front;
}
free(q);
Q.count--;
return true;
}
int main() {
LinkQueue Q;
InitSqQueue(Q);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
cout << "遍历队列:";
LNode *p = Q.front->Next;
while (p != NULL) {
cout << p->data << " ";
p = p->Next;
}
cout << endl;
cout << "队列长度为:" << Q.count << endl;
int e;
DeQueue(Q, e);
cout << "删除元素" << e << ":";
p = Q.front->Next;
while (p != NULL) {
cout << p->data << " ";
p = p->Next;
}
cout << endl;
cout << "队列长度为:" << Q.count << endl;
return 0;
}