//单向队列
#include<stdio.h>
#include<stdlib.h>
typedef struct queue
{
int* elements;
int capacity;
int head;
int rear;
}queue;
void QueueInit(queue* q, int capacity);
void QueueDestroy(queue* q);
void QueuePush(queue* q, int elem);
int QueuePop(queue* q);
void QueueInit(queue* q,int capacity)
{
q->capacity = capacity;
q->head = q->rear = 0;
q->elements = (int*)malloc(sizeof(int) * capacity);
if (q->elements == NULL)
exit(EXIT_FAILURE);
}
void QueueDestroy(queue* q)
{
q->capacity = 0;
q->head = q->rear = 0;
if (q->elements)
free(q->elements);
q->elements = NULL;
}
void QueuePush(queue* q, int elem)
{
int* new_elements;
// 判断是否为满,是则扩容
if (q->rear == q->capacity)
{
q->capacity *= 2;
new_elements = (int*)realloc(q->elements, sizeof(int) * q->capacity);
if (new_elements == NULL)
exit(EXIT_FAILURE);
q->elements = new_elements;
}
q->elements[q->rear++] = elem;
}
int QueuePop(queue* q)
{
if (q->head == q->rear)
{
printf("no elements\n");
exit(EXIT_FAILURE);
}
return q->elements[q->head++];
}
基础数据结构——顺序队列(单向)代码实现C
最新推荐文章于 2024-09-28 20:31:26 发布