数据结构-队列(C语言实现)
定义
一种先进先出的数据结构
具体实现(C语言)
表头文件
#include<stdio.h>
#include<malloc.h>
typedef struct Node //定义节点
{
int data;
Node *PNEXT;
}NODE,*PNODE;
typedef struct Quene //定义队列
{
PNODE First;
PNODE Last;
}QUENE,*PQUENE;
初始化
void init(PQUENE pQ)
{
pQ->First = (PNODE)malloc(sizeof(NODE));
pQ->Last = pQ->First;
pQ->Last->PNEXT = NULL;
}
进队
void EnQuene(PQUENE pQ,int val)
{
PNODE newnode = (PNODE)malloc(sizeof(NODE));
newnode->data = val;
pQ->Last->PNEXT = newnode;
pQ->Last = newnode;
newnode->PNEXT = NULL;
}
判断队列是否为空
int ifEmpty(PQUENE pQ)
{
if(pQ->First == pQ->Last)
return 1;
else
return 0;
}
出队
int DeQuene(PQUENE pQ)
{
if(ifEmpty(pQ))
{
printf("队列已空,出队失败");
return 0;
}
else
{
PNODE p;
p = pQ->First->PNEXT;
pQ->First->PNEXT = p->PNEXT;
int a = p->data;
free(p);
return a;
}
}
队列数据遍历
void traverse(PQUENE pQ)
{
PNODE p = pQ->First->PNEXT;
while(p->PNEXT != NULL)
{
printf("%d ",p->data);
p = p->PNEXT;
}
printf("%d ",p->data);
printf("\n");
}
销毁队列
void destory(PQUENE pQ)
{
while(pQ->First != pQ->Last)
{
PNODE p = pQ->First;
pQ->First = p->PNEXT;
free(p);
}
free(pQ->First);
}
主程序
int main()
{
QUENE quene;
init(&quene);
EnQuene(&quene,1);
EnQuene(&quene,2);
EnQuene(&quene,3);
traverse(&quene);
int a = DeQuene(&quene);
printf("%d值已出列\n",a);
traverse(&quene);
destory(&quene);
return 0;
}
运行结果