C语言链队列实现:入队和出队操作详解
C语言链队列实现:入队和出队操作详解
本文将详细介绍使用C语言实现链队列的入队和出队操作,并提供完整的代码示例,帮助您理解链队列的结构和基本操作。
链队列的定义
链队列是一种线性数据结构,它使用链表来存储元素,并遵循先进先出(FIFO)的原则。在链队列中,队头和队尾分别指向链表的头结点和尾结点。
代码实现
#include <stdio.h>
#include <malloc.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode * next;
}LNode,*LinkList;
typedef struct
{
LinkList front,rear; /* 队头、队尾指针 */
}LinkQueue;
/* 带头结点的链队列的基本操作 */
Status InitQueue(LinkQueue *Q)
{
/* 构造一个空队列Q */
LinkList p;
p=(LNode*)malloc(sizeof(LNode));
p->next=NULL;
(*Q).rear=(*Q).front=p;
return OK;
}
Status List(LinkList L)
{
LinkList p;
if(!L) return ERROR;
p=L->next;
while(p)
{
printf(' %d',p->data);
p=p->next;
}
printf('
');
return OK;
}
int QueueLenth(LinkQueue Q)
{
int n=0;
LinkList p;
if(Q.rear==Q.front)
return 0;
p=Q.front->next;
while(p)
{
n++;
p=p->next;
}
return n;
}
/* 入队操作 */
Status QueueInsert(LinkQueue *Q, ElemType e)
{
LinkList p = (LNode*)malloc(sizeof(LNode));
if(!p)
return ERROR;
p->data = e;
p->next = NULL;
(*Q).rear->next = p;
(*Q).rear = p;
return OK;
}
/* 出队操作 */
Status QueueDelete(LinkQueue *Q, ElemType *e)
{
if((*Q).front == (*Q).rear)
return ERROR;
LinkList p = (*Q).front->next;
(*e) = p->data;
(*Q).front->next = p->next;
if((*Q).rear == p)
(*Q).rear = (*Q).front;
free(p);
return OK;
}
int main()
{
int x;
LinkQueue Q;
InitQueue(&Q);
QueueInsert(&Q,1);QueueInsert(&Q,2);QueueInsert(&Q,3);
List(Q.front );
QueueDelete( &Q,&x);
printf(' %d %d
',x,QueueLenth(Q));
QueueDelete(&Q,&x);QueueDelete(&Q,&x);
printf(' %d %d
',x,QueueLenth(Q));
return 0;
}
代码解释
- InitQueue(): 初始化一个空队列。
- QueueInsert(): 将一个元素插入到队列尾部。
- QueueDelete(): 从队列头部删除一个元素。
总结
本教程详细介绍了使用C语言实现链队列的入队和出队操作,并提供了完整的代码示例。希望通过本教程的学习,您能够深入理解链队列的结构和基本操作。
原文地址: https://www.cveoy.top/t/topic/pl8x 著作权归作者所有。请勿转载和采集!