记录自己所学,无详细讲解
队列的实现--使用动态链表
1.项目目录文件
、
2.头文件 queue.h
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
struct QueueNode
{int data;struct Queue* next;
};
typedef struct QueueNode QueueNode;
typedef struct Queue
{QueueNode* head;QueueNode* tail;
}Queue;
void QueueInit(Queue* p); //初始化
void QueuePush(Queue* p,int n); //队尾入队列
void QueuePop(Queue* p); //队头出队列
int QueueFront(Queue* p); //队列头元素
int QueueBack(Queue* p); //队列列尾元素
bool QueueEmpty(Queue* p); //是否为空队列
3.函数定义源文件 queue.c
#include "queue.h"
void QueueInit(Queue* p)
{p->head = NULL;p->tail = NULL;
}
void QueuePush(Queue* p, int n)
{QueueNode * newnode = (QueueNode*)malloc(sizeof(QueueNode));assert(newnode);newnode->data = n;newnode->next = NULL;if (p->tail == NULL){p->head = newnode;p->tail = newnode;}else{(p->tail)->next = newnode;p->tail = (p->tail)->next;}
}
void QueuePop(Queue* p)
{assert(p); assert(p->head);QueueNode* newhead = (p->head)->next;free(p->head);p->head = newhead;if (p->head == NULL){p->tail = NULL;}
}
int QueueFront(Queue* p)
{assert(p->head);return (p->head)->data;
}
int QueueBack(Queue* p)
{assert(p->tail);return (p->tail)->data;
}
bool QueueEmpty(Queue* p)
{assert(p);return p->head == NULL;
}
4.函数调用测试源文件test.c
#include "queue.h"
int main()
{Queue p;QueueInit(&p);QueuePush(&p,3);QueuePush(&p, 4);QueuePush(&p, 5);QueuePop(&p);QueuePop(&p);QueuePop(&p);printf("%3d",QueueFront(&p));printf("%3d",QueueBack(&p));if (QueueEmpty(&p)){printf("为空");}else{printf("不为空");}return 0;
}