数据结构 顺序队列(计数器版)

在实现循环队列时,为了区分队列为空和队列满的情况,我们通常会浪费一个位置。也就是说,如果队列的总容量是100,那么实际上只能存储99个元素。这是因为我们需要保留一个位置来判断队列是满的还是空的。如果我们不这样做,那么在队列满和队列空时,frontrear 指针都会指向同一个位置,这将导致无法区分这两种状态。

解决方法:增加一个计数器

增加一个额外的变量来记录队列中当前元素的数量,以达到区分队列满和队列空。

头文件

​
#pragma once
#define MAX 100
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
typedef int data_type;
typedef struct {
	data_type element[MAX];
	int front, rear, count;
}queue, * queue_ptr;
extern void queue_ini(queue_ptr p);
extern void print_queue(queue_ptr p);
extern int is_empty(queue_ptr p);
extern int is_full(queue_ptr p);
extern data_type in_queue(queue_ptr p, data_type data);
extern data_type out_queue(queue_ptr p);
extern data_type get_front(queue_ptr p);

​

源文件

#include "Lk.h"
void queue_ini(queue_ptr p)
{
	p->front = p->rear = p->count = NULL;
}

int is_empty(queue_ptr p)
{
	return (p->count==0) ? 1 : 0;//empty 1
}

int is_full(queue_ptr p)
{
	return (p->count==MAX) ? 1 : 0;//full 1
}

data_type in_queue(queue_ptr p, data_type data)
{
	if (is_full(p))return -1;
	else {
		p->element[p->rear] = data;
		p->rear = (p->rear + 1) % MAX;
		printf("%d已入队\n", data);
		p->count++;
	}
	return data;
}

data_type out_queue(queue_ptr p)
{
	if (is_empty(p))return -1;
	else {
		data_type v = p->element[p->front];
		p->front = (p->front + 1) % MAX;
		printf("已出队%d\n", v);
		p->count--;
		return v;
	}

}


void print_queue(queue_ptr p)
{
	if (is_empty(p))return;
	else {
		for (int i = p->front; i != p->rear; i = (i + 1) % MAX)
		{
			printf("%d\n", p->element[i]);
		}
	}
}
data_type get_front(queue_ptr p)
{
	printf("Front: %d\n", p->element[p->front]);
	return p->element[p->front];
}

main

#include"Lk.h"
int main() {
	//extern void queue_creat(queue_ptr p);
	//extern int is_empty(queue_ptr p);
	//extern int is_full(queue_ptr p);
	//extern data_type in_queue(queue_ptr p, data_type data);
	//extern data_type out_queue(queue_ptr p);
	//extern void print_queue(queue_ptr p);
	//extern data_type get_front(queue_ptr p);
	clock_t start = clock();
	queue_ptr s = (queue_ptr)malloc(sizeof(queue));
	queue_ini(s);
	for (int i = 0; i < 99; i++) {
		in_queue(s, i);
	}
	for (int j = 0; j < 50; j++)
	{
		out_queue(s);
	}
	get_front(s);

	clock_t end = clock();
	double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
	printf("\n程序运行时间: %f 秒\n", time_taken);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值