完成了顺序和链式的队列

This commit is contained in:
lzy
2024-04-17 15:12:21 +08:00
parent f13a690864
commit 9fd115d30b
10 changed files with 469 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
# 方便起见一般都会先定义编译器链接器
CC = gcc
LD = gcc
# 正则表达式表示目录下所有.c文件相当于SRCS = main.c a.c b.c
SRCS = $(wildcard *.c)
# OBJS表示SRCS中把列表中的.c全部替换为.o相当于OBJS = main.o a.o b.o
OBJS = $(patsubst %c, %o, $(SRCS))
# 可执行文件的名字
TARGET = main
# .PHONE伪目标具体含义百度一下一大堆介绍
.PHONY:all clean
# 要生成的目标文件
all: $(TARGET)
# 第一行依赖关系冒号后面为依赖的文件相当于Hello: main.o a.o b.o
# 第二行规则:$@表示目标文件,$^表示所有依赖文件,$<表示第一个依赖文件
$(TARGET): $(OBJS)
$(LD) -o $@ $^
# 上一句目标文件依赖一大堆.o文件这句表示所有.o都由相应名字的.c文件自动生成
%.o:%.c
$(CC) -c $^
# make clean删除所有.o和目标文件
clean:
rm -f $(OBJS) $(TARGET)

View File

@@ -0,0 +1,39 @@
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
int main()
{
queue *sq;
datatype arr[] = {2, 34, 89, 12};
int i;
sq = qu_create();
if (NULL == sq)
exit(1);
for (i = 0; i < sizeof(arr) / sizeof(*arr); i++)
qu_enqueue(sq, &arr[i]);
qu_travel(sq);
datatype tmp;
qu_dequeue(sq, &tmp);
printf("DEQUEUE:%d\n", tmp);
#if 0
datatype tmp = 100;
int ret;
ret = qu_enqueue(sq, &tmp);
if (-1 == ret)
printf("Queue is full!\n");
else
qu_travel(sq);
#endif
qu_destroy(sq);
exit(0);
}

View File

@@ -0,0 +1,72 @@
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
queue *qu_create()
{
queue *sq;
sq = malloc(sizeof(*sq));
if (NULL == sq)
return NULL;
sq->head = 0;
sq->tail = 0;
return sq;
}
int qu_isempty(queue *sq)
{
return (sq->head == sq->tail);
}
int qu_enqueue(queue *sq, datatype *x)
{
if ((sq->tail + 1) % MAXSIZE == sq->head)
return -1;
sq->tail = (sq->tail + 1) % MAXSIZE;
sq->data[sq->tail] = *x;
return 0;
}
int qu_dequeue(queue *sq, datatype *x)
{
if (qu_isempty(sq))
return -1;
sq->head = (sq->head + 1) % MAXSIZE;
*x = sq->data[sq->head];
return 0;
}
void qu_travel(queue *sq)
{
if (sq->head == sq->tail)
return;
int i;
i = (sq->head + 1) % MAXSIZE;
while (i != sq->tail)
{
printf("%d ", sq->data[i]);
i = (i + 1) % MAXSIZE;
}
printf("%d \n", sq->data[i]);
}
void qu_clear(queue *sq)
{
sq->head = sq->tail;
}
void qu_destroy(queue *sq)
{
free(sq);
}

View File

@@ -0,0 +1,29 @@
#ifndef QUEUE_H__
#define QUEUE_H__
#define MAXSIZE 5
typedef int datatype;
typedef struct node_st
{
datatype data[MAXSIZE];
int head, tail;
} queue;
queue *qu_create();
int qu_isempty();
int qu_enqueue(queue *, datatype *);
int qu_dequeue(queue *, datatype *);
void qu_travel(queue *);
void qu_clear(queue *);
void qu_destroy(queue *);
#endif