一、概述
队列是数据结构中最常用的一种算法,核心是FFO(First In First Out),即先进先出,顶部出队列,底部入队列。
二、操作


三、代码
头文件
#ifndef _LIST_H_
#define _LIST_H_
#include <stdio.h>
#include <stdlib.h>
#define SUCCESS 0
#define FAIL -1
//链表的数据结构
typedef struct ListNode *pListNode;
typedef int DataType;//链表中的数据类型
typedef struct ListNode{
DataType *data;
pListNode next;
}sListNode;
typedef struct List{
sListNode *head;
int dataNum;
}sList;
void InitList();
int Insert(const DataType data);
int Delete(const DataType data);
int Query(const DataType *data);
void Clear();
int Size();
void Print();
#endif
源文件
#include "list.h"
#include <string.h>
static sList gList;
static void DataCopy(DataType *newData, const DataType *oldData){
memcpy(newData,oldData,sizeof(DataType));
}
static int DataCmp(DataType *newData, const DataType *oldData){
return memcmp(newData,oldData,sizeof(DataType));
}
void InitList(){
gList.dataNum = 0;
gList.head = NULL;
}
int Insert(const DataType data){
pListNode node = (pListNode)malloc(sizeof(sListNode));
node->data = (DataType *)malloc(sizeof(DataType));
DataCopy(node->data,&data);
node->next = NULL;
if(NULL == gList.head)
{
gList.head = node;
}
else
{
node->next = gList.head;
gList.head = node;
}
gList.dataNum++;
return SUCCESS;
}
int Delete(const DataType data){
if(NULL == gList.head){
return FAIL;
}
pListNode head = gList.head;
pListNode next = NULL;
if(0 == DataCmp(gList.head->data,&data))
{
gList.head = head->next;
free(head->data);
free(head);
gList.dataNum--;
return SUCCESS;
}
else
{
next = head->next;
while(next){
if(0 == DataCmp(next->data,&data))
{
head->next = next->next;
free(next->data);
free(next);
gList.dataNum--;
return SUCCESS;
}
head = next;
next = head->next;
}
}
return FAIL;
}
int Query(const DataType *data){
pListNode node = gList.head;
while(node){
if(0 == DataCmp(node->data,data)){
return SUCCESS;
}
}
return FAIL;
}
void Clear(){
pListNode node = NULL;
while(gList.head)
{
node = gList.head;
gList.head = gList.head->next;
free(node->data);
free(node);
}
InitList();
}
int Size(){
return gList.dataNum;
}
void Print(){
pListNode node = gList.head;
printf("size:%d\n",gList.dataNum);
while(node)
{
printf("%d ",*node->data);
node = node->next;
}
printf("\n");
}
测试文件
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
InitList();
Insert(1);
Insert(2);
Print();
Delete(2);
Print();
Delete(1);
Print();
return 0;
}
测试结果

本文深入探讨了队列这一核心数据结构,详细介绍了其先进先出(FFO)的工作原理,以及通过链表实现的基本操作,包括插入、删除和查询等关键功能。文章提供了完整的代码实现,展示了如何在实际应用中构建和使用队列。
1854

被折叠的 条评论
为什么被折叠?



