C语言队列的实现
对于C语言的队列来说,也有顺序存储和链表存储两种方式。
顺序存储容量固定,链表存储随时分配释放更加灵活。
下面是链表实现的队列初始化、入队、出队函数实现:
#include<stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node
{
int val;
struct Node* next;
}NODE, * PNODE;
typedef struct Queue
{
PNODE front, rear;
}QUEUE, *PQUEUE;
void InitQueue(PQUEUE queue)
{
queue->front = queue->rear = (PNODE)malloc(sizeof(NODE));
if (queue->front == NULL)
{
printf("没有足够内存空间,错误\n");
}
queue->front->next = NULL;
}
void InsertQueue(PQUEUE queue, int val)
{
PNODE tmp = (PNODE)malloc(sizeof(NODE));
if (tmp == NULL)
{
printf("无足够内存空间,错误\n");
}
tmp->val = val;
tmp->next = NULL;
queue->rear->next = tmp;
queue->rear = queue->rear->next;
tmp = NULL;
}
int DeleteQueue(PQUEUE queue)
{
if (queue->front == queue->rear)
{
printf("队列为空\n");
}
PNODE p = NULL;
int val;
p = queue->front->next;
queue->front->next = p->next;
val = p->val;
free(p);
p = NULL;
return val;
}
int main(void)
{
QUEUE queue;
InitQueue(&queue);
InsertQueue(&queue, 1);
InsertQueue(&queue, 2);
InsertQueue(&queue, 3);
for (int i = 0; i < 3; i++)
printf("%d\n", DeleteQueue(&queue));
return 0;
}
注意:在定义队列的时候,不能定义PQUEUE,因为他是一个指针,在定义时需要指向NULL,但是指向NULL的指针是不允许对内部的结点进行任何操作的,因此需要定义QUEUE。
再通过&queue将队列指针传递进去。
浙公网安备 33010602011771号