循环队列的C语言实现

本文实现了循环队列的C语言实现。主要功能入队与出队。欢迎关注个人博客:https://guotianyu-2020.github.io。

1.代码部分

循环队列结构体的定义

循环队列的结构

typedef struct {
	int* base;
	int front;  // Integer front points at the first position of existed elements.
	int rear;  // Integer rear points at the empty position to be inserted.
}Queue;

初始化函数,接受一个分配好空间的循环队列,对内部进行初始化。

Queue* Initial(Queue* que)
{
	que->front = que->rear = 0;
	que->base = (int*)malloc(MAXSIZE * sizeof(int));
	if (!que->base) { printf("ERROR!"); }
	return que;
}

入队、出队函数:

void EnQueue(Queue* que)
{
	int e;
	// The method of using less than one spatial element is used to distinguish empty queues from full queues.
	if ((que->rear + 1) % MAXSIZE == que->front) { printf("Queue is full. Fail to insert.\n"); }
	else {
		printf("Input the number you want to add:\n");
		scanf_s("%d", &e);
		setvbuf(stdin, NULL, _IOFBF, 512);
		que->base[que->rear] = e;
		que->rear = (que->rear + 1) % MAXSIZE;  // Make queue a circle.
		printf("%d is added in.\n", e);
	}
}


void DeQueue(Queue* que)
{
	int e;
	if (que->front == que->rear) { printf("Queue is empty.\n"); }
	e = que->base[que->front];
	que->front = (que->front + 1) % MAXSIZE;
	printf("Number %d is deleted.\n", e);
}

经main函数验证正确。

int main() 
{
	Queue* sq = (Queue*)malloc(sizeof(Queue));
	sq = Initial(sq);
	int i;
	/*
	When EnQueue for the sixth time, it will be prompted that the queue is full, 
	indicating that the method of using less than one spatial element to distinguish 
	between empty queue and full queue is successful.
	*/
	for (i = 1; i <= 5; i++)
	{
		EnQueue(sq);
	}
	DeQueue(sq);
	DeQueue(sq);
	DeQueue(sq);
	EnQueue(sq);
	EnQueue(sq);
	DeQueue(sq);
	DeQueue(sq);
	EnQueue(sq);
	DeQueue(sq);
	EnQueue(sq);
	EnQueue(sq);
	DeQueue(sq);
	DeQueue(sq);
	return 0;
}

2.反思与改进

  1. 失败的show函数。试图通过一个函数按顺序展现队列的元素,但是由于空缺位置的存在与其位置的不确定性,未能实现相关功能。期望有时间的话进一步改进算法,也欢迎大佬们给出建议。

    // An unsuccessful try. Don't know how to show the queue correctly.
    void ShowQueue(Queue* que)
    {
    	int i, j, k;
    	k = QueueLength(que);
    	if (que->front < que->rear) 
    	{
    		for (i = que->front; i <= k; i++)
    		{
    			printf("Order: %d.\n", que->base[i]);
    		}
    	}
    	else if(que->front > que->rear)
    	{
    		for (i = que->front; i <= MAXSIZE; i++)
    		{
    			printf("Order:%d.\n", que->base[i]);
    		}
    		for (j = 0; j < que->rear; j++)
    		{
    			printf("Order:%d.\n", que->base[j]);
    		}
    	}
    	else {
    		printf("Empty.\n");
    	}
    }
    
    1. 什么时候分配内存,什么时候直接定义:

      当初次使用结构体或者在函数内部需要对结构体内部成员进行赋值时要现malloc,当这个新结构体只是用来承载已存在的结构体的内容时(如直接指向同一内容:p = q)不需要malloc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值