C语言实现基于顺序表的顺序队列
linkqueue.h文件
#pragma once
typedef char linkType;
typedef struct linkNode
{
linkType data;
struct linkNode *next;
}linkNode;
//初始化函数
void linkQueueInit(linkNode **qhead);
//销毁函数
void linkQueueDestroy(linkNode **qhead);
//入队列函数
void linkQueuePush(linkNode **qhead,linkType value);
//出队列函数
void linkQueuePop(linkNode **qhead);
//取队首元素函数
int linkQueueGetTop(linkNode *qhead,linkType *value);
linkqueue.c文件
#include<stdio.h>
#include<stdlib.h>
#include"linkqueue.h"
#define Test_Header printf("\n============%s============\n",__FUNCTION__);
//初始化函数
void linkQueueInit(linkNode **qhead)
{
if(qhead == NULL)
{
//非法输入
return;
}
*qhead = NULL;
}
//销毁函数
void linkQueueDestroy(linkNode **qhead)
{
if(qhead == NULL)
{
//非法输入
return;
}
//遍历链式队列,释放每一个节点
linkNode *cur = *qhead;
for(;cur != NULL;cur = cur->next)
{
free(cur);
}
*qhead = NULL;
}
//创建新的节点函数
linkNode *CreateNode(linkType value)
{
linkNode *new_node = (linkNode*)malloc(sizeof(linkNode));
new_node->next = NULL;
new_node->data = value;
}
//入队列函数(链表的尾插)
void linkQueuePush(linkNode **qhead,linkType value)
{
if(qhead == NULL)
{
//非法输入
return;
}
if(*qhead == NULL)
{
//空队列则直接创建一个新的节点,为链式栈的第一个节点
*qhead = CreateNode(value);
return;
}
//遍历链式队列找到链式队列的最后一个元素
linkNode *cur = *qhead;
for(;cur->next != NULL;cur = cur->next)
;
//创建一个新的节点
linkNode *new_node = CreateNode(value);
//将链式队列的最后一个节点的next指向该新节点即可完成链式队列的尾插(即入队列操作)
cur->next = new_node;
}
//出队列函数(链表的头删)
void linkQueuePop(linkNode **qhead)
{
if(qhead == NULL)
{
//非法输入
return;
}
if(*qhead == NULL)
{
//空队列
return;
}
//定义一个新的指针指向链式队列的第一个节点
linkNode *to_delete = *qhead;
//将链式队列的头结点重新指向原第一个节点的下一个
*qhead = to_delete->next;
//将原第一个节点释放
free(to_delete);
}
//取队首元素函数
int linkQueueGetTop(linkNode *qhead,linkType *value)
{
if(qhead == NULL)
{
//空队列
return 0;
}
*value = qhead->data;
return 1;
}
//打印
void Print(linkNode *qhead,const char *msg)
{
printf("[%s]\n",msg);
if(qhead == NULL)
{
return;
}
linkNode *cur = qhead;
for(;cur != NULL;cur = cur->next)
{
printf("%c ",cur->data);
}
printf("\n\n");
}
//以下为测试函数
void TestLinkQueue()
{
Test_Header;
linkNode *qhead;
//初始化链式队列
linkQueueInit(&qhead);
//链式队列入队列测试
linkQueuePush(&qhead,'a');
linkQueuePush(&qhead,'b');
linkQueuePush(&qhead,'c');
linkQueuePush(&qhead,'d');
Print(qhead,"push four elems:a b c d");
//链式队列出队列测试
linkQueuePop(&qhead);
linkQueuePop(&qhead);
Print(qhead,"pop twice");
linkQueuePop(&qhead);
linkQueuePop(&qhead);
Print(qhead,"repop twice");
//链式队列取队首元素测试
linkType value;
linkQueuePush(&qhead,'a');
linkQueuePush(&qhead,'b');
Print(qhead,"push two elems:a b");
int ret = linkQueueGetTop(qhead,&value);
printf("expected ret:1 , actual ret:%d\n",ret);
printf("expected top:a , actual top:%c\n",value);
linkQueuePop(&qhead);
linkQueuePop(&qhead);
Print(qhead,"pop twice");
ret = linkQueueGetTop(qhead,&value);
printf("expected ret:0 , actual ret:%d\n",ret);
}
//主函数调用测试函数
int main()
{
TestLinkQueue();
return 0;
}
测试结果如下图: