linkqueue.h
#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
union
{
int len;
datatype data;
};
struct node *next;
}node;
typedef struct queue
{
node *head;
node *tail;
}linkqueue,*linkqueueptr;
//创建链式队列
linkqueueptr create();
//判空
int empty(linkqueueptr Q);
//入队
void push(linkqueueptr Q,datatype e);
//遍历
void show(linkqueueptr Q);
//出列
void pop(linkqueueptr Q);
//队列长度
int size(linkqueueptr Q);
//销毁
void freeQ(linkqueueptr Q);
#endif
linkqueue.c
#include "linkqueue.h"
//创建链式队列
linkqueueptr create()
{
linkqueueptr Q=(linkqueueptr)malloc(sizeof(linkqueue));
if(Q==NULL)
{
printf("创建失败\n");
return NULL;
}
Q->head=(node *)malloc(sizeof(node));
if(Q->head==NULL)
{
printf("申请失败\n");
free(Q);
return NULL;
}
Q->head->len=0;
Q->head->next=NULL;
Q->tail=Q->head;
printf("创建成功\n");
return Q;
}
//判空
int empty(linkqueueptr Q)
{
if(Q==NULL)
{
printf("判空失败\n");
return -1;
}
return Q->head==Q->tail;
}
//入队
void push(linkqueueptr Q,datatype e)
{
if(Q==NULL)
{
printf("入队失败\n");
return;
}
node *p=(node *)malloc(sizeof(node));
if(p==NULL)
{
printf("申请失败\n");
return;
}
p->data=e;
p->next=NULL;
Q->tail->next=p;
Q->tail=p;
Q->head->len++;
}
//遍历
void show(linkqueueptr Q)
{
if(Q==NULL||empty(Q))
{
printf("遍历失败\n");
return;
}
node *q=Q->head;
while(q->next!=NULL)
{
q=q->next;
printf("%d ",q->data);
}
printf("\n");
}
//出列
void pop(linkqueueptr Q)
{
if(Q==NULL||empty(Q))
{
printf("出列失败\n");
return;
}
printf("%d出列\n",Q->head->next->data);
node *q=Q->head->next;
Q->head->next=q->next;
free(q);
q=NULL;
Q->head->len--;
}
//队列长度
int size(linkqueueptr Q)
{
if(Q==NULL)
{
printf("计算失败\n");
return -1;
}
return Q->head->len;
}
//销毁
void freeQ(linkqueueptr Q)
{
if(Q==NULL)
{
printf("销毁失败\n");
return;
}
while(Q->head->next!=NULL)
pop(Q);
free(Q->head);
Q->head=NULL;
free(Q);
Q=NULL;
printf("销毁成功\n");
}
main.c
#include "linkqueue.h"
int main()
{
linkqueueptr Q=create();
push(Q,1);
push(Q,2);
push(Q,3);
show(Q);
pop(Q);
show(Q);
int d=size(Q);
printf("size=%d\n",d);
freeQ(Q);
}