#include <stdio.h>//链表队列
#include <stdlib.h>
typedef int data_t;
// 定义链式队列的节点结构
typedef struct node
{
data_t data;
struct node* next;
} node_t;
// 定义链式队列结构
typedef struct
{
node_t* head; // 队列头指针
node_t* tail;
int size; // 队列中元素个数
int count; //结点个数
}LQueue_t;
// 函数声明
int LQueue_Create(LQueue_t* s,int);
int LQueue_Push(LQueue_t* s, data_t data);
int LQueue_Pop(LQueue_t* s, data_t* data);
void LQueue_Free(LQueue_t* s);
int LQueue_isfull(LQueue_t*);
int LQueue_isempty(LQueue_t*);
int LQueue_isfull(LQueue_t* s)
{
return s->count == s->size;
}
int LQueue_isempty(LQueue_t* s)
{
return s->count == 0;
}
int LQueue_Create(LQueue_t* s,int sz)
{
if (s == NULL)
return -1;
s->head = s->tail = NULL;
s->size = sz;
s->count = 0;
return 0;
}
int LQueue_Push(LQueue_t* s, data_t data)//尾插入队
{
if (s == NULL)
return -1;
if (LQueue_isfull(s))
return -1;
node_t* p = (node_t*)malloc(sizeof(node_t));
if (p == NULL)
{
return -1;
}
p->data = data;
p->next = NULL;
if (s->tail == NULL)//唯一结点
s->head = s->tail = p;
else
{
s->tail->next = p;
s->tail = p;
}
s->count++;
return 0;
}
int LQueue_Pop(LQueue_t* s, data_t* data)//头结点出队
{
if (s == NULL)
return -1;
if (LQueue_isempty(s))
return -1;
node_t* p = s->head;
s->head = p->next;
*data = p->data;
free(p);
s->count--;
return 0;
}
void LQueue_Free(LQueue_t* s)
{
if (s == NULL)
return ;
node_t* f = s->head, * b = NULL;
while (f)
{
b = f;
f = f->next;
free(b);
}
s->head = s->tail = NULL;
s->size = 0;
s->count = 0;
}
int main() {
LQueue_t s;
// 创建队列
if (LQueue_Create(&s,13) != 0) {
printf("栈创建失败\n");
return -1;
}
// 测试入队
for (int i = 1; i < 12; i++) {
if (LQueue_Push(&s, i) != 0) {
printf("入栈失败: %d\n", i);
break;
}
}
// 测试出队
printf("出栈顺序: ");
while (s.size > 0) {
data_t data;
if (LQueue_Pop(&s, &data) == 0) {
printf("%3d", data);
}
}
printf("\n");
// 回收队列
LQueue_Free(&s);
return 0;
}
运行结果: