栈和队列
本节内容是继双向环链之后的拓展内容:栈和队列的实现也是在双向环链的基础上实现的。双向环链详解:双向环链 课程来源:bilibilili李慧芹
栈
栈的特点:先进后出
栈的创建
STACK* stack_create(int initsize)
{
return llist_create(initsize);
}
入栈
int stack_push(STACK *ptr ,const void*data)
{
return llist_insert(ptr,data,LLIST_FORWARD);
}
出栈
static int always_match(const void *p1,const void *p2)
{
return 0;
}
int stack_pop(STACK *ptr ,void *data)
{
return llist_fetch(ptr,(void *)0,always_match,data);
}
栈的销毁
void stack_destory(STACK *ptr)
{
llist_destory(ptr);
}
栈操作代码测试
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define NAMESIZE 32
int ret;
struct score_st
{
int id;
char name[NAMESIZE];
int math;
int chinese;
};
static void printf_s(void *record)
{
struct score_st *r = record;
printf("%d %s %d %d \n",r->id,r->name,r->math,r->chinese);
}
int main()
{
STACK *st;
struct score_st tmp;
st = stack_create(sizeof(struct score_st));
if (st == NULL)
{
exit(1);
}
for (int i = 0; i < 7; i++)
{
tmp.id = i;
snprintf(tmp.name,NAMESIZE,"std%d",i);
tmp.math = rand()%100;
tmp.chinese = rand()%100;
if(stack_push(st,&tmp))
exit(1);
}
while (1)
{
ret = stack_pop(st,&tmp);
if (ret == -1)
break;
printf_s(&tmp);
}
stack_destory(st);
exit(0);
}
输出结果:
队列
队列的特点:先进先出
队创建
QUEUE * queue_create(int size)
{
return llist_create(size);
}
入队
int queue_en(QUEUE *ptr,const void * data)
{
return llist_insert(ptr,data,LLIST_BACKWARD);
}
出队
static int alwaws_match(const void *p1 ,const void *p2)
{
return 0;
}
int queue_de(QUEUE *ptr,void *data)
{
return llist_fetch(ptr,(void*)0,alwaws_match,data);
}
队列的删除
void queue_destory(QUEUE *ptr)
{
llist_destory(ptr);
}
代码测试
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
#define MAXSIZE 32
struct score_st
{
int id;
char name[MAXSIZE];
int math;
int chinese;
};
static void printf_s(void *record)
{
struct score_st *r = record;
printf("%d %s %d %d \n",r->id,r->name,r->math,r->chinese);
}
int main()
{
QUEUE *qu;
int ret;
struct score_st tmp;
qu = queue_create(sizeof(struct score_st));
if (qu == NULL)
exit(1);
for (int i = 0; i < 7; i++)
{
tmp.id = i;
snprintf(tmp.name,MAXSIZE,"stu%d",i);
tmp.math = rand()%100;
tmp.chinese = rand()%100;
if(queue_en(qu,&tmp)!=0)
break;
}
while (1)
{
ret = queue_de(qu,&tmp);
if (ret == -1)
break;
printf_s(&tmp);
}
queue_destory(qu);
exit(0);
}
输出结果:
与栈的输出正好相反~~
|