相关概念
为了实现队列的功能、所以在链式存储里可以采用头插、尾删或者尾插、头删的方法实现。但不管是尾插还是尾删都需要每次遍历链表,这样做时间效率比较低下,所以我们可以定义两个指针(head、tail),head用于保存头结点的地址、tail用于保存最后一个结点的地址,这样做可以省去遍历整个链表所造成的资源浪费。
相关操作
创建结点结构体
创建一个空的链式队列
入队
判断链式队列是否为空
出队
相关代码
linkqueue.h
#ifndef _LINKQUEUE_H_
#define _LINKQUEUE_H_
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int datatype;
//定义结点结构体
typedef struct node{
datatype data;
struct node* next;
}linknode;
//定义结构体,用于返回指针
typedef struct{
linknode *head;
linknode *tail;
}linkqueue;
linkqueue * linkqueueCreate();
void linkqueueInput(linkqueue *lq, datatype value);
bool linkqueueIsEmpty(linkqueue *lq);
datatype linkqueueOutput(linkqueue *lq);
void linkqueuePrint(linkqueue *lq);
#endif
linkqueue.c
#include"linkqueue.h"
//创建一个空的链式队列
linkqueue * linkqueueCreate(){
//给要操作链表的指针(两个)申请空间,用于返回主函数
linkqueue *lq = (linkqueue *)malloc(sizeof(linkqueue));
lq->head = (linknode *)malloc(sizeof(linknode));
lq->tail = lq->head;
lq->head->next = NULL;
return lq;
}
//入队
void linkqueueInput(linkqueue *lq, datatype value){
linknode *temp = (linknode *)malloc(sizeof(linknode));
temp->data = value;
temp->next = NULL;
//尾插法
//1.tail对应结点的指针保存新插入结点的地址
lq->tail->next = temp;
temp->next = NULL;
//2.tail保存最后一个结点的地址
lq->tail = temp;
return ;
}
//判断队列是否为空
bool linkqueueIsEmpty(linkqueue *lq){
return ((lq->head->next == NULL) && (lq->head == lq->tail)) ? true : false;
}
//出队
datatype linkqueueOutput(linkqueue *lq){
if(linkqueueIsEmpty(lq)){
printf("the queue is empty\n");
return (datatype)-1;
}
datatype value;
linknode *temp = lq->head->next;
value = temp->data;
lq->head->next = temp->next;
free(temp);
//出队后要判断队列是否为空,若为空,要将tail归位(指向head的指向)
if(lq->head->next == NULL){
lq->tail = lq->head;
}
return value;
}
//遍历链式队列
void linkqueuePrint(linkqueue *lq){
linknode *temp = lq->head;
while(temp->next != NULL){
temp = temp->next;
printf("%d ", temp->data);
}
putchar(10);
return ;
}
main.c
#include"linkqueue.h"
int main(int argc, char const *argv[]){
linkqueue *lq = linkqueueCreate();
linkqueueInput(lq, 100);
linkqueueInput(lq, 200);
linkqueueInput(lq, 300);
linkqueueInput(lq, 400);
linkqueueInput(lq, 500);
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
linkqueueInput(lq, 100);
linkqueueInput(lq, 200);
linkqueueInput(lq, 300);
linkqueueInput(lq, 400);
linkqueueInput(lq, 500);
linkqueuePrint(lq);
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
printf("output value : %d\n",linkqueueOutput(lq));
return 0;
}
Makefile
OBJ=linkqueue
CFLAGS += -g -Wall
${OBJ}:${OBJ}.o main.o
%*.o:%*.c
.PHONY:clean
clean:
${RM} *.o ${OBJ} core