在C语言中不能用动态分配的一维数组来实现循环队列,如果我们需要使用循环队列,那么就必须设定一个最大的队列长度;如果我们没有办法估计所用队列的最大长度的话,应该使用链队
链队的结构和实现代码
#include <stdio
.h
>
#include <stdlib
.h
>
#define OK
1
#define ERROR
0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef char Elemtype;
typedef struct QNode{
Elemtype
data;
struct QNode
*next;
}QNode,
*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue
*q)
{
q
->front
= q
->rear
= (QueuePtr)malloc(sizeof(QNode));
if (
!q
->rear)
return ERROR;
q
->rear
->next
= NULL;
return OK;
}
Status DestoryQueue(LinkQueue
*q)
{
while (q
->front){
q
->rear
= q
->front
->next;
free(q
->front);
q
->front
= q
->rear;
}
return OK;
}
Status EnQueue(LinkQueue
*q, Elemtype e)
{
QueuePtr newNode
= (QueuePtr)malloc(sizeof(QNode));
if (
!newNode)
return ERROR;
newNode
->data = e;
newNode
->next
= NULL;
(
*q)
.rear
->next
= newNode;
(
*q)
.rear
= newNode;
return OK;
}
Status DeQueue(LinkQueue
*q, Elemtype
*e)
{
QueuePtr p;
if (q
->front
== q
->rear)
return ERROR;
p
= q
->front
->next;
*e
= p
->data;
q
->front
->next
= p
->next;
if (q
->rear
== p)
q
->rear
= q
->front;
free(p);
}
Status DispQueue(LinkQueue q)
{
QueuePtr p;
if (q
.front
->next
== NULL)
return ERROR;
p
= q
.front
->next;
while (p){
printf(
"%c ", p
->data);
p
= p
->next;
}
printf(
"\n");
return OK;
}
int main()
{
LinkQueue q;
Elemtype e;
printf(
"初始化链队\n");
InitQueue(
&q);
printf(
"入队\n");
EnQueue(
&q,
'a');
EnQueue(
&q,
'b');
EnQueue(
&q,
'c');
EnQueue(
&q,
'd');
EnQueue(
&q,
'e');
EnQueue(
&q,
'f');
EnQueue(
&q,
'g');
printf(
"链队中元素为\n");
DispQueue(q);
printf(
"出队操作\n");
DeQueue(
&q,
&e);
DeQueue(
&q,
&e);
DeQueue(
&q,
&e);
DeQueue(
&q,
&e);
printf(
"链队中元素为\n");
DispQueue(q);
printf(
"销毁链队\n");
system(
"pause");
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-1298088.html