循环顺序队列
#define MAX 8
typedef int datatype;
typedef struct
{
datatype data[MAX];
int front;
int tail;
}duilie;
#include "dui.h"
#include <stdio.h>
#include <stdlib.h>
//创建
duilie *create()
{
duilie *D = (duilie *)malloc(sizeof(duilie));
if(NULL==D)
{
printf("创建失败\n");
return NULL;
}
D->front = 0;
D->tail = 0;
printf("创建成功\n");
return D;
}
//判空
int empty(duilie *D)
{
return D->front == D->tail ?1:0;
}
int full(duilie *D)
{
return (D->tail+1)%MAX == D->front ?1:0;
}
//入队
int push(duilie *D,datatype e)
{
if(NULL==D || full(D))
{
printf("入队失败\n");
return -1;
}
D->data[D->tail] = e;
D->tail = (D->tail+1)%MAX;
printf("入队成功\n");
return 0;
}
//遍历
void show(duilie *D)
{
if(NULL==D || empty(D))
{
printf("遍历失败\n");
return ;
}
for(int i=D->front;i != D->tail;i=(i+1)%MAX)
{
printf("%d ",D->data[i]);
}
printf("\n");
}
//出队
int pop(duilie *D)
{
//判断逻辑
if(NULL==D || empty(D))
{
printf("出队失败\n");
return -1;
}
//出队
printf("%d出队成功\n", D->data[D->front]);
D->front = (D->front+1)%MAX;
return 0;
}
//求长度
int len(duilie *D)
{
return (D->tail - D->front + MAX)%MAX;
}
//销毁
void destroy(duilie *D)
{
if(NULL!=D)
{
free(D);
D = NULL;
}
printf("销毁成功\n");
}
链式队列
typedef int datatype;
typedef struct Node
{
union
{
datatype data;
int len;
}
struct Node *next;
};
typedef struct
{
Node *head;
Node *tail;
}linkdui;
#include "liandui.h"
#include <stdio.h>
#include <stdlib.h>
//创建
linkdui *create()
{
linkdui *l = (linkdui*)malloc(sizeof(linkdui));
if(NULL==l)
{
printf("创建队伍失败\n");
return NULL;
}
//
l->head = (Node *)malloc(sizeof(Node));
if(NULL==l->head)
{
printf("创建结点失败\n");
return NULL;
}
//初始化
l->head->len = 0;
l->head->next = NULL;
l->tail = l->head;
printf("创建成功\n");
return l;
}
//队列判空
int empty(linkdui *l)
{
return l->head==l->tail ?1:0;
}
//申请结点
Node *node_apply(datatype e)
{
Node *p = (Node*)malloc(sizeof(Node));
if(NULL==p)
{
printf("结点申请失败\n");
return NULL;
}
//数据封装进结点
p->data = e;
p->next = NULL;
return p;
}
//入队
int push(linkdui *l,datatype e)
{
if(NULL==l)
{
printf("入队失败\n");
return -1;
}
//申请结点封装数据
Node *p = node_apply(e);
//新结点连接到链表尾部
l->tail->next = p;
//更新队列尾指针
l->tail = p;
//链表长度变化
l->head->len++;
printf("入队成功\n");
return 0;
}
//遍历
void show(linkdui *l)
{
if(NULL==l || empty(l))
{
printf("遍历失败\n");
return ;
}
Node *q = l->head->next;
while(q != NULL)
{
printf("%d ",q->data);
q = q->next;
}
printf("\n");
}
//出队
int pop(linkdui *l)
{
if(NULL==l || empty(l))
{
printf("出队失败\n");
return -1;
}
Node *p = l->head->next;
l->head->next = p->next;
free(p);
//判断是否为空
if(l->head->next == NULL)
{
l->tail=l->head;
}
p = NULL;
l->head->len--;
return 0;
}
//销毁
void free(linkdui *l)
{
if(NULL==l)
{
return ;
}
while(l->head != l->tail)
{
pop(l);
}
free(l->head);
free(l);
l = NULL;
printf("释放成功\n");
}