#include <iostream>
#include <malloc.h>
using namespace std;
//声明链队数据结点类型
typedef struct dNode {
char data;
struct dNode* next;
}dataNode;
//声明链队类型
typedef struct {
dataNode* front;
dataNode* rear;
}linkQuNode;
//初始化链队
void InitQueue(linkQuNode*& q) {
q = (linkQuNode*)malloc(sizeof(linkQuNode));
q->front = q->rear = NULL;
}
//判断链队是否为空
bool EmptyQueue(linkQuNode* q) {
return(q->rear == NULL);
}
//进队操作
bool EnterQueue(linkQuNode*& q, char c) {
dataNode* s = NULL;
s = (dataNode*)malloc(sizeof(dataNode));
s->data = c;
s->next = NULL;
if (q->rear == NULL)//如果链队为空,则新结点即是首结点,又是尾结点
{
q->front = q->rear = s;
}
else { //将s结点链到队尾,并将rear指向他
q->rear->next = s;
q->rear = s;
}
return true;
}
//出队操作
bool OutQueue(linkQuNode*& q, char &c) {
dataNode* p = NULL;
//如果链队为空
if (q->rear == NULL)
{
return false;
}
p = q->front;//p指向第一个数据节点
if (q->front == q->rear)//队列中只有一个节点时
{
q->front = q->rear = NULL;
}
else//队列中有多个结点时
{
q->front = q->front->next;
}
c = p->data;
free(p);
return true;
}
//销毁队列
void DestroyQueue(linkQuNode*& q) {
dataNode* pre = q->front, * p = NULL;
if (pre!=NULL)//如果q->front为空,代表只有一个头结点,此时直接释放头结点
{
p = pre->next;
while (p!= NULL)
{
free(pre);
pre = p;
p = p->next;
}
free(pre);
}
free(q);
}
int main() {
linkQuNode* q;
char c = '\0';
InitQueue(q);
cout << (EmptyQueue(q) ? "空" : "非空") << endl;
EnterQueue(q, 'a');
EnterQueue(q, 'b');
EnterQueue(q, 'c');
EnterQueue(q, 'd');
EnterQueue(q, 'e');
cout << (EmptyQueue(q) ? "空" : "非空") << endl;
//出队列
if (OutQueue(q, c)) {
cout << c << endl;
}
if (OutQueue(q, c)) {
cout << c << endl;
}
if (OutQueue(q, c)) {
cout << c << endl;
}
if (OutQueue(q, c)) {
cout << c << endl;
}
if (OutQueue(q, c)) {
cout << c << endl;
}
cout << (EmptyQueue(q) ? "空" : "非空") << endl;
DestroyQueue(q);
return 0;
}
c链队
于 2023-05-19 20:24:47 首次发布