创建链式队列需要定义两个指针分别指向队头和队尾。然后创建结点,再进行判空。链式队列没有限制,所以不需要判满。因为存在先进先出(尾部进,头部出)的顺序,所以入队即尾插。然后进行出队操作。
//创建链表
#include "link_que.h"
node_t create_linkque()
{
node_t H=(node_t)malloc(sizeof(node));
if(H==NULL)
{
printf("内存申请失败\n");
return NULL;
}
H->data=-1;
H->next=NULL;
return H;
}
//创建队头指针和队尾指针
que create_que(node_t H)
{
que Q=(que)malloc(sizeof(link_que));
if(Q==NULL)
{
printf("内存申请失败\n");
return NULL;
}
Q->front=H;
Q->rear=H;
return Q;
}
//创建结点
node_t create_node(int data)
{
node_t p=(node_t)malloc(sizeof(node));
if(p==NULL)
{
printf("内存申请失败\n");
return NULL;
}
p->data=data;
p->next=NULL;
return p;
}
//判空
int empty_linkque(que Q,node_t H)
{
if(Q==NULL)
{
printf("入参为空\n");
return -1;
}
return Q->front==Q->rear&&Q->rear==H?1:0;
}
//入队,尾插
void push_linkque(que Q,int data,node_t H)
{
if(Q==NULL)
{
printf("入参为空\n");
return;
}
node_t p=create_node(data);
//当链队为空的情况
if(empty_linkque(Q,H))
{
//Q->fornt=H,因为链队为空的时候Q->front和Q->next都指向H
Q->front->next=p;
Q->front=p;
Q->rear=p;
}
else
{
Q->rear->next=p;
Q->rear=p;
}
}
//出队
void pop_linkque(que Q,node_t H)
{
if(Q==NULL)
{
printf("入参为空\n");
return;
}
if(empty_linkque(Q,H))
{
printf("链队为空\n");
return;
}
if(Q->rear==Q->front&&Q->rear!=H)
{
//当链队中只有一个元素的时候
printf("出队的元素为%d\n",Q->front->data);
Q->front=H;
Q->rear=H;
H->next=NULL;
return;
}
printf("出队的元素为%d\n",Q->front->data);
//保存要删除的结点
node_t dele =Q->front;
//Q->front指向第二个结点
Q->front=Q->front->next;
//头结点重新指向,现在链队中的第一个结点
H->next=Q->front;
free(dele);
}
//打印
void print_linkque(que Q,node_t H)
{
if(Q==NULL)
{
printf("入参为空\n");
return;
}
if(!empty_linkque(Q,H))
{
node_t p=Q->front;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
}
//清空
进行清空操作时,可以利用while循环和调用出队函数来实现。
void clean_linkeque(que Q,node_t H)
{
if(Q==NULL)
{
printf("入参为空\n");
return;
}
while(!empty_linkque(Q,H))
{
pop_linkque(Q,H);
}
}
//销毁
销毁也可以向利用清空函数来实现。只需要再将H删除。
void deatory_que(que *Q,node_t *H)
{
if(Q==NULL||*Q==NULL||H==NULL||*H==NULL)
{
printf("error\n");
return;
}
clean_linkeque(*Q,*H);
free(*Q);
free(*H);
*Q=NULL;
*H=NULL;
}