#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int datatype;
typedef struct Node
{
union
{
datatype data;
int len;
};
struct Node *next;
}Node;
typedef struct
{
Node* Head;
Node* Tail;
}LinkQueue, *LinkQueuePtr;
//创建队列
LinkQueuePtr queue_create();
//判空
int queue_empty(LinkQueuePtr LQ);
//入队
int queue_push(LinkQueuePtr LQ, datatype e);
//出队
int queue_pop(LinkQueuePtr LQ);
//遍历队
void queue_show(LinkQueuePtr LQ);
//销毁队伍
void queue_free(LinkQueuePtr LQ);
#endif
#include "linkqueue.h"
//创建队
LinkQueuePtr queue_create()
{
LinkQueuePtr LQ = (LinkQueuePtr)malloc(sizeof(LinkQueue));
if(NULL==LQ)
{
printf("创建失败\n");
return NULL;
}
LQ->Head = (Node*)malloc(sizeof(Node));
if(NULL == LQ->Head)
{
printf("创建失败\n");
return NULL;
}
LQ->Head->len = 0;
LQ->Head->next =NULL;
LQ->Tail = LQ->Head;
printf("队伍创建成功\n");
return LQ;
}
//判空
int queue_empty(LinkQueuePtr LQ)
{
if(NULL==LQ || NULL==LQ->Head)
{
printf("所给队列不合法\n");
return -1;
}
return LQ->Head == LQ->Tail;
}
//入队
int queue_push(LinkQueuePtr LQ, datatype e)
{
if(NULL==LQ)
{
printf("所给队列不合法\n");
return 0;
}
Node*p = (Node*)malloc(sizeof(Node));
if(NULL==p)
{
printf("入队失败\n");
return 0;
}
p->data = e;
p->next = NULL;
LQ->Tail->next = p;
LQ->Tail = p;
LQ->Head->len++;
printf("入队成功\n");
return 1;
}
//出队
int queue_pop(LinkQueuePtr LQ)
{
if(NULL==LQ || queue_empty(LQ))
{
printf("出队失败\n");
return -1;
}
Node *p = LQ->Head->next;
LQ->Head->next = p->next;
printf("%d出队成功\n",p->data);
free(p);
p=NULL;
LQ->Head->len--;
if(LQ->Head->next == NULL)
{
LQ->Tail = LQ->Head;
}
return 1;
}
//遍历队
void queue_show(LinkQueuePtr LQ)
{
if(NULL==LQ || queue_empty(LQ))
{
printf("遍历失败\n");
return ;
}
printf("链队中的元素分别是:");
Node *q=LQ->Head->next;
while(q != NULL)
{
printf("%d\t",q->data);
q = q->next;
}
printf("\n");
}
//销毁队伍
void queue_free(LinkQueuePtr LQ)
{
if(NULL==LQ)
{
printf("释放失败\n");
return;
}
while(!queue_empty(LQ))
{
queue_pop(LQ);
}
free(LQ->Head);
LQ->Head = LQ->Tail = NULL;
free(LQ);
LQ = NULL;
printf("释放成功\n");
}
#include "linkqueue.h"
int main(int argc, const char *argv[])
{
LinkQueuePtr LQ = queue_create();
if(NULL==LQ)
{
return -1;
}
queue_push(LQ, 3);
queue_push(LQ, 6);
queue_push(LQ, 9);
queue_push(LQ, 5);
queue_pop(LQ);
queue_show(LQ);
queue_free(LQ);
LQ = NULL;
queue_show(LQ);
return 0;
}