#pragma once
#include <stdbool.h>
//利用带有头节点的单链表实现队列,队头为第一个数据节点
typedef struct Node
{
int data;
struct Node *next;
}Node; //数据节点
typedef struct HNode
{
struct Node *front; //队头指针
struct Node *rear; //队尾指针
}HNode,*PLQueue; //头节点
void InitQueue(PLQueue pl);
//入队
bool Push(PLQueue pl, int val);
//获取队头的值,但不删除
bool GetTop(PLQueue pl, int *rtval);
//获取队头的值,且删除
bool Pop(PLQueue pl, int *rtval);
//判空
bool IsEmpty(PLQueue pl);
.cpp
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "lsqueue.h"
/*
typedef struct Node
{
int data;
struct Node *next;
}Node; //数据节点
typedef struct HNode
{
struct Node *front; //队头指针
struct Node *rear; //队尾指针
}HNode,*PLQueue; //头节点
*/
void InitQueue(PLQueue pl)
{
assert(pl != NULL);
pl->front = NULL;
pl->rear = NULL;
}
//入队
bool Push(PLQueue pl, int val)
{
Node *p = (Node *)malloc(sizeof(Node));
p->data = val;
p->next = NULL;
if(IsEmpty(pl))
{
pl->front = p;
pl->rear = p;
}
else
{
pl->rear->next = p;
pl->rear = p;
}
return true;
}
//获取队头的值,且删除
bool Pop(PLQueue pl, int *rtval)
{
if(IsEmpty(pl))
{
return false;
}
if(rtval != NULL)
{
*rtval = pl->front->data;
}
Node *p = pl->front;
free(p);
if(pl->front == NULL) //已经删除最后一个节点
{
pl->rear = NULL;
}
return true;
}
//获取队头的值 不删除
bool GetPop(PLQueue pl, int *rtval)
{
assert(pl != NULL);
if(IsEmpty(pl))
{
return false;
}
if(rtval != NULL)
{
*rtval = pl->front->data;
}
return true;
}
bool IsEmpty(PLQueue pl)
{
return pl->front == NULL;
}
main.c
#include <stdio.h>
#include "lsqueue.h"
int main()
{
HNode head;
InitQueue(&head);
for(int i = 0; i < 15; i++)
{
Push(&head, i);
}
int tmp;
while(!IsEmpty(&head))
{
Pop(&head, &tmp);
printf("%d\n", tmp);
}
return 0;
}