#ifndef _LINKED_QUEUE_H_
#define _LINKED_QUEUE_H_
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct node
{
union
{
int len;
datatype data;
};
struct node *next;
}node;
typedef struct linked_queue
{
node *head;
node *tail;
}lq;
node *nodeapply(datatype c);
lq *create();
int is_empty(lq *Q);
int lq_push(lq *Q,node *p);
datatype lq_pop(lq *Q);
int show(lq *Q);
#endif
ubuntu@ubuntu:~/ds/linked_queue$ cat *.c
#include"linked_queue.h"
lq *create()
{
lq *Q=(lq *)malloc(sizeof(lq));
if(NULL==Q)
{
printf("申请链队失败\n");
return NULL;
}
Q->head=(node *)malloc(sizeof(node));
if(NULL==Q->head)
{
printf("申请头结点空间失败\n");
free(Q);
return NULL;
}
Q->head->len=0;
Q->head->next=NULL;
Q->tail=Q->head;
printf("创建成功\n");
return Q;
}
#include"linked_queue.h"
int is_empty(lq * Q)
{
if(NULL==Q)
{
printf("所给链队不合法\n");
return -1;
}
return (Q->head==Q->tail);
}
#include"linked_queue.h"
datatype lq_pop(lq *Q)
{
datatype out;
node *temp;
if(is_empty(Q)!=-1)
{
if(is_empty(Q)==0)
{
out=Q->head->next->data;
temp=Q->head->next;
Q->head->next=Q->head->next->next;
if(Q->tail==temp)
{
Q->tail=Q->head;
}
free(temp);
temp=NULL;
return out;
}
printf("链队为空\n");
}
}
#include"linked_queue.h"
int lq_push(lq *Q,node *p)
{
if(is_empty(Q)!=-1)
{
Q->tail->next=p;
Q->tail=Q->tail->next;
Q->tail->next=NULL;
(Q->head->len)++;
}
return -1;
}
#include"linked_queue.h"
int main()
{
lq *Q=create();
lq_push(Q,nodeapply(1));
lq_push(Q,nodeapply(2));
lq_push(Q,nodeapply(3));
lq_push(Q,nodeapply(4));
lq_push(Q,nodeapply(5));
lq_pop(Q);
lq_pop(Q);
lq_pop(Q);
lq_pop(Q);
lq_pop(Q);
show(Q);
return 0;
}
#include"linked_queue.h"
node *nodeapply(datatype c)
{
node *p=(node *)malloc(sizeof(node));
if(NULL==p)
{
printf("申请失败\n");
return NULL;
}
p->next=NULL;
p->data=c;
return p;
}
#include"linked_queue.h"
int show(lq *Q)
{
node *q=Q->head->next;
if(is_empty(Q)!=-1)
{
if(is_empty(Q)==1)
{
printf("链队为空\n");
return 0;
}
while(q!=NULL)
{
printf("%d ",q->data);
q=q->next;
}
putchar(10);
return 1;
}
return -1;
}