像栈一样,队列也是表。使用队列时插入和删除分别在队列的两端进行
队列是一种先进先出(FIFO)的数据结构
队列的链表实现方式太过于简单,本文介绍数组的实现方式
实现思路:
1.维护两个索引,front代表队列的首部,rear代表队列的尾部
2.入队时,rear + 1,队列当前大小 + 1
3.出队时,front + 1, 队列当前大小 + 1
4.通过队列当前大小判断队列是否已满,来保证入队时新元素不会覆盖旧元素
5.将front和rear的递增后的索引对队列总大小取模,保证不会下标越界,同时实现循环数组
代码实现
1.队列结构体
typedef struct { int *data; // 数组 int front; // 队列首部索引 int rear; // 队列尾部索引 int size; // 队列当前大小 int capacity; // 队列总大小 } queue;
2.创建队列
void init_queue(queue *queue) { queue->data = (int *)malloc(INITIAL_CAPACITY * sizeof(int)); queue->front = 0; queue->rear = -1; queue->size = 0; queue->capacity = INITIAL_CAPACITY; }
3.入队
int enqueue(queue *queue, int value) { if (queue->size == queue->capacity) { expand(queue); } queue->rear = (queue->rear + 1) % queue->capacity; // 循环数组 queue->data[queue->rear] = value; queue->size++; }
4.出队
int enqueue(queue *queue, int value) { if (queue->size == queue->capacity) { expand(queue); } queue->rear = (queue->rear + 1) % queue->capacity; // 循环数组 queue->data[queue->rear] = value; queue->size++; }
5.销毁队列
void freeQueue(queue *queue) { free(queue->data); queue->data = NULL; queue->front = 0; queue->rear = -1; queue->size = 0; queue->capacity = 0; }
6.测试
int main() { queue queue; initQueue(&queue); enqueue(&queue, 10); enqueue(&queue, 20); enqueue(&queue, 30); printf("Front element is %d\n", peek(&queue)); printf("Dequeued element is %d\n", dequeue(&queue)); printf("Front element is now %d\n", peek(&queue)); freeQueue(&queue); return 0; }