5.数据结构之队列

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

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


Queue* initQueue(int n)
{
	Queue *q = (Queue*)malloc(sizeof(Queue));
	q->data = (int*)malloc(sizeof(int) * n);
	q->size = n;
	q->head = q->tail = 0;
	return q;
}

void freeQueue(Queue* q)
{
	if (!q) return;
	free(q->data);
	free(q);
	return;
}


bool expand(Queue* q)
{
	if (!q) return false;
	int size = q->size;
	int* p = NULL;
	while (size)
	{
		p = (int *)malloc(sizeof(int) * (q->size + size));
		if (p) break;
		size >>= 1;
	}
	if (!q) return false;
	
	//搬运数据到新的地方
	int j=0;
	for (int i = q->head; i != q->tail; i = (i + 1) % q->size, j++)
	{
		p[j] = q->data[i];
	}

	free(q->data);
	q->data = p;
	q->head = 0;
	q->tail = j;
	q->size += size;
	return true;
}

bool push(Queue* q, int val)
{
	if (!q) return false;
	
	//队列满了
	if ((q->tail + 1) % q->size == q->head)
	{
		if (!expand(q)) return 0;
		printf("expand success!,after expand size %d\n", q->size);
	}

	q->data[q->tail] = val;
	q->tail = (q->tail+1) % q->size;
	
	return true;
}

bool isEmpty(Queue* q)
{
	return !q || q->head == q->tail;
}


int  pop(Queue* q)
{
	int tmp = q->data[q->head];
	q->head = (q->head + 1) % q->size;
	return tmp;
}


void showQueue(Queue* q)
{
	if (isEmpty(q)) return;
	printf("Queue;[");
	int i = q->head;
	for (; i != q->tail; i = (i + 1) % q->size) {
		i != q->head && printf(",");
		printf("%d", q->data[i]);
	}
	printf("]\n");
}

int main()
{
	srand(time(0));
	Queue* q = initQueue(1);

	int cnt = 20;
	while (cnt--)
	{
		int val=rand() % 100;
		int opt = rand() % 4;
		switch (opt)
		{
		case 0:
		case 1:
		case 2:
			printf("push %d,res=%s\n", val, push(q, val)?"SUC":"ERR");
			break;
		case 3:
			isEmpty(q) ? printf("pop nothing!\n") : printf("pop %d\n", pop(q));
			break;
		}

		showQueue(q);
	}
	

	freeQueue(q);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值