#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
typedef struct Queue {
int *data;
int head, tail, length, count;
}Queue;
void init(Queue *q, int length) {
q->data = (int *)malloc(sizeof(int) * length);
q->length = length;
q->head = 0;
q->tail = -1;
q->count = 0;
}
int push(Queue *q, int element) {
if (q->count >= q->length) {
return ERROR;
}
q->tail = (q->tail + 1) % q->length;
q->data[q->tail] = element;
q->count++;
return OK;
}
void output(Queue *q) {
int i = q->head;
do {
printf("%d ", q->data[i]);
i = (i + 1) % q->length;
} while(i != (q->tail + 1) % q->length);
printf("\n");
}
int front(Queue *q) {
return q->data[q->head];
}
void pop(Queue *q) {
q->head = (q->head + 1) % q->length;
q->count--;
}
int empty(Queue *q) {
return q->count == 0;
}
void clear(Queue *q) {
free(q->data);
free(q);
}
int main() {
Queue *q = (Queue *)malloc(sizeof(Queue));
init(q, 100);
for (int i = 1; i <= 10; i++) {
push(q, i);
}
output(q);
if (!empty(q)) {
printf("%d\n", front(q));
pop(q);
}
output(q);
clear(q);
return 0;
}
循環(huán)隊列
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 隊列是一種特殊的線性表,只能在頭尾兩端進行操作隊尾(rear):只能從隊尾添加元素,一般叫做 enQueue,入隊...
- //循環(huán)隊列順序表示,隊列初始化,求隊列長度,入隊,出隊,打印隊列中的元素,求隊頭元素 include <stdi...
- 1.設(shè)計你的循環(huán)隊列 Leet Code 原題鏈接Leet Code 原題動畫演示視頻設(shè)計你的循環(huán)隊列實現(xiàn)。 循環(huán)...
- 1.循環(huán)隊列的精髓在于,front指針指向?qū)嶋H的頭元素,擴容重新排列。 2.計算實際index的時候封裝著實際in...
- 棧 隊列 鏈?zhǔn)疥犃?4 . 循環(huán)隊列