队列链表
将队列以链表的形式连接起来。
队列链表的入队只能在链表的尾部,出队只能在链表的头部。
因此队列链表需要两个指针,一个指向头,一个指向尾。
通过对头尾指针的动态移动,来操作队列的入队和出队。
//节点结构体声明
typedef struct Node
{
TYPE data; //存放的数据
struct Node* next; //节点指针
}Node;
//链表构成
typedef struct QueueList
{
Node* front; //头指针
Node* rear; //尾指针
size_t cnt; //队列长度
}QueueList;
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define TYPE int
typedef struct Node
{
TYPE data;
struct Node* next;
}Node;
Node* create_node(TYPE data)
{
Node* node = malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
typedef struct QueueList
{
Node* front;
Node* rear;
size_t cnt;
}QueueList;
//创建
QueueList* create_queue(void)
{
QueueList* queue = malloc(sizeof(QueueList));
queue->front = NULL;
queue->rear = NULL;
queue->cnt = 0;
return queue;
}
//队空
bool empty_queue(QueueList* queue)
{
return 0 == queue->cnt;
}
//入队
void push_queue(QueueList* queue,TYPE data)
{
Node* node = create_node(data);
if(0 == queue->cnt)
{
queue->front = node;
queue->rear = node;
}
else
{
queue->rear->next = node;
queue->rear = node;
}
queue->cnt++;
}
//出队
bool pop_queue(QueueList* queue)
{
if(0 == queue->cnt)
return false;
Node* node = queue->front;
queue->front = queue->front->next;
queue->cnt--;
free(node);
return true;
}
//队头
TYPE front_queue(QueueList* queue)
{
return queue->front->data;
}
//队尾
TYPE rear_queue(QueueList* queue)
{
return queue->rear->data;
}
//销毁
void destroy_queue(QueueList* queue)
{
while(!empty_queue(queue))
pop_queue(queue);
free(queue);
}
int main(int argc,const char* argv[])
{
QueueList* queue = create_queue();
for(int i=0; i<10; i++)
{
push_queue(queue,rand()%100);
printf("rear:%d\n",rear_queue(queue));
}
while(!empty_queue(queue))
{
printf("front:%d\n",front_queue(queue));
pop_queue(queue);
}
destroy_queue(queue);
}