队列
1.顺序表队列:空间占用小
2.链表队列:空间占用大
FIFO (first in first out ) 先进先出,先来先服务 (区别于顺序表的性质结构) 或者称 LILO (last in last out)
线性结构,一片连续的内存空间,size 队列的容量大小、head、tail、count(表示存了几个元素即length)。出队,从队首出队。 入队,从队尾入队 。
注意:队列的性质本身就不支持随机访问
队列编程实现两种方式:
1.head指向第一个元素下标,tail指向最后一个元素的下标
2.head指向第一个元素下标,tail指向最后一个元素的下一个元素下标。程序用第二种方式来编程。 head == tail就是空队列
队列的假溢出 ----->循环队列 ,%实现,滑动;count计数(循坏队列用)
为解决假溢出,使用循坏队列(链表结构的队列,没有循坏队列,仅顺序表结构才有)
普通顺序表队列
普通队列(顺序表来管理数据)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Queue {
int *data; // 一片连续的存储空间
int length, head, tail;
} Queue;
Queue *init_Queue(int n) {
// if (q == NULL) return 0; 来判断队列是否创建成功
// malloc() 创建失败返回NULL地址
Queue *q = (Queue *)malloc(sizeof(Queue));
q->data = (int *)malloc(sizeof(int) * n);
q->length = n;
q->head = q->tail = 0;
return q;
}
// 判断队列是否为空
int empty(Queue *q) {
return q->head == q->tail;
}
// 返回队首元素
int front(Queue *q) {
return q->data[q->head];
}
// 入队
int push(Queue *q, int val) {
if (q == NULL) return 0;
if (q->tail == q->length) return 0; // 队列存满
q->data[q->tail] = val;
q->tail += 1; // q->data[q->tail++] = val;
return 1;
}
// 出队
int pop(Queue *q) {
if (q == NULL) return 0;
if (empty(q)) return 0;
q->head += 1;
return 1;
}
void clear(Queue *q) {
if (q == NULL) return ;
free(q->data);
free(q);
return ;
}
void output(Queue *q) {
printf("Queue : [");
for (int i = q->head; i < q->tail; i++) {
i != q->head && printf(" ");
printf("%d", q->data[i]);
}
printf("]\n");
return ;
}
int main() {
srand(time(0));
#define MAX_OP 20
Queue *q = init_Queue(MAX_OP);
for (int i = 0; i < MAX_OP; i++) {
int op = rand() % 4;
int val = rand() % 100;
switch (op) {
case 0:
case 1:
case 2: {
printf("push %d to Queue = %d\n", val, push(q,val));} break;
case 3: {
if (empty(q)) {
printf("fail to pop a item!\n");
} else {
printf("success to pop a item : %d\n", front(q));
pop(q);
}
} break;
}
output(q), printf("\n");
}
#undef MAX_OP
clear(q);
return 0;
}
push 4 to Queue = 1
Queue : [4]
success to pop a item : 4
Queue : []
push 74 to Queue = 1
Queue : [74]
push 51 to Queue = 1
Queue : [74 51]
push 45 to Queue = 1
Queue : [74 51 45]
success to pop a item : 74
Queue : [51 45]
push 6 to Queue = 1
Queue : [51 45 6]
success to pop a item : 51
Queue : [45 6]
push 19 to Queue = 1
Queue : [45 6 19]
push 35 to Queue