参考《大话数据结构》:
环境:ubuntu16.04 vim
文件名称:linkqueue.h linkqueue.c main.c Makefile(放到同一个目录下)
实现功能:链式队列的初始化,入队操作和出队操作
1.linkqueue.h头文件
#ifndef __LINKQUEUE_HEAD__
#define __LINKQUEUE_HEAD__
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
#define OK 0
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
/*结点结构*/
typedef struct QNode //结点结构
{
ElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct //队列的链表结构
{
QueuePtr front, rear; //队头、队尾
}LinkQueue;
/*
*初始化一个空队列q
*q [IN, OUT]执行操作的链表队列
*/
extern Status QueueInit(LinkQueue *q);
/*
*插入一个新的队尾元素e
*q [IN, OUT]执行操作的链表队列
*e [IN]要插入队尾的元素
*/
extern Status EnQueue(LinkQueue *q, ElemType e);
/*
*队列不为空时,删除队头的元素
*q [IN, OUT]执行操作的链表队列
*e [IN, OUT]要删除的队头元素
*/
extern Status DeQueue(LinkQueue *q, ElemType *e);
#endif
2.linkqueue.c文件
#include "linkqueue.h"
/*初始化头结点*/
Status QueueInit(LinkQueue *q)
{
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if (p == NULL)
{
printf("malloc failed!\n");
return ERROR;
}
p->data = 0;
q->front = p;
q->rear = p;
p->next = NULL;
return OK;
}
/*插入元素e为q的新的队尾元素*/
Status EnQueue(LinkQueue *q, ElemType e)
{
QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
if (!s) //存储分配失败
{
printf("malloc failed!\n");
return ERROR;
}
s->data = e;
s->next = NULL;
q->rear->next = s; //把拥有元素e新结点s赋值给原队尾结点的后继
q->rear = s; //把当前的s设置为队尾结点,rear指向s
return OK;
}
/*若队列不空,删除q的队头元素,用e返回其值,并返回OK,否则返回ERROR*/
Status DeQueue(LinkQueue *q, ElemType *e)
{
QueuePtr p;
if (q->front == q->rear)
{
printf("队列为空!\n");
return ERROR;
}
p = q->front->next; //先将欲删除的队头结点暂存给p
*e = p->data; //将欲删除的队头结点的值赋值给e
q->front->next = p->next; //将原队头结点后继p->next赋值给头结点后继
if (q->rear == p) //若队头是队尾,则删除后将rear指向头结点
{
q->rear = q->front;
}
free(p);
return OK;
}
3.main.c文件
#include "linkqueue.h"
int main()
{
LinkQueue q;
//初始化一个队列
if (QueueInit(&q))
{
printf("init queue failed!\n");
return ERROR;
}
//向队尾列插入一个元素
if (EnQueue(&q, 3))
{
printf("enqueue failed!\n");
return ERROR;
}
//向队尾列插入一个元素
if (EnQueue(&q, 4))
{
printf("enqueue failed!\n");
return ERROR;
}
//将队头的元素删除
ElemType e = 0;
if (DeQueue(&q, &e))
{
printf("dequeue failed!\n");
return ERROR;
}
printf("要删除队头的元素为:e:%d\n", e);
//将队头的元素删除
if (DeQueue(&q, &e))
{
printf("dequeue failed!\n");
return ERROR;
}
printf("要删除队头的元素为:e:%d\n", e);
//将队头的元素删除
if (DeQueue(&q, &e))
{
printf("dequeue failed!\n");
return ERROR;
}
printf("要删除队头的元素为:e:%d\n", e);
return OK;
}
4.Makefile文件
#Makefile for building programmings
OBJS=linkqueue.o main.o
CC=gcc
CFLAGS=-Wall -g
TARGET=linkqueue
TARGET:$(OBJS)
$(CC) $(OBJS) -o $(TARGET)
linkqueue.o:linkqueue.c linkqueue.h
$(CC) $(CFLAGS) -c $< -o $@
main.o:main.c linkqueue.h
$(CC) $(CFLAGS) -c $< -o $@
.PHONY:clean
clean:
rm *.o linkqueue
5.运行结果