C语言-队列

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

typedef struct Queue {
	int *data;
	int head, tail, length, cnt;
} Queue;

Queue *init(int n) {
	Queue *q = (Queue *)malloc(sizeof(Queue));
	q->data = (int *)malloc(sizeof(int));
	q->length = n;
	q->head = q->tail = q->cnt = 0;
	return q;
}
int front(Queue *q) {
	return q->data[q->head];
}

int empty(Queue *q) {
	return q->cnt == 0;
}


int expand(Queue *q) { //扩容没写
	return 0;
}

int push(Queue *q, int val) {
	if(q == NULL) return 0;
	if(q->cnt == q->length) {
		if(!expand(q)) return 0;
		printf("expand successfully ! Queue->size(%d)\n",q->length);
	}
	q->data[q->tail++] = val;
	if(q->tail == q->length) q->tail = 0;
	q->cnt += 1;
	return 1;
}

int pop(Queue *q) {
	if(q == NULL) return 0;
	if(empty(q)) return 0;
	q->head++;
	if(q->head == q->length) q->head = 0;
	q->cnt -= 1;
	return 1;
}

void output(Queue *q) {
	printf("Queue:[");
	for(int i = q->head, j = 0; j < q->cnt; i++, j++) {
		j && printf(", ");
		printf("%d", q->data[i % q->length]);
	}
	printf("]\n");
	return ;
}

void clear(Queue *q) {
	if(q==NULL) return ;
	free(q->data);
	free(q);
	return ;
}


int main() {
	srand(time(0));
#define max_op 20
	Queue *q = init(max_op);
	for (int i = 0; i < max_op * 2; i++) {
		int val = rand() % 100;
		int op = rand() % 4;
		switch (op) {
			case 0:
			case 1:
			case 2: {
				printf("push %d to the Queue = %d\n", val, push(q, val));
			}
			break;
			case 3: {
				printf("pop %d from the Queue = %d\n",front(q),pop(q));
			}
			break;
		}
		output(q), printf("\n");
	}
#undef max_op
	clear(q);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值