队列简单实现

本文介绍了一种使用C++实现的简单队列数据结构,并演示了如何进行元素的入队和出队操作。通过具体代码展示了队列初始化、判断空满状态、获取长度等关键功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// MyQueue.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

#define  QUEUELEN 15

// data
typedef struct {
	char name[15];
	int age;
}DATA;

typedef struct {
	DATA data[QUEUELEN];
	int head;
	int tail;
}SQType;

// init
SQType *SQTypeInit()
{
	SQType *q;
	if(q = (SQType *)malloc(sizeof(SQType)))
	{
		q->head = 0;
		q->tail = 0;
		return q;
	}
	cout<<"malloc error!"<<endl;
	return (SQType*)NULL;
}

// EMpty
int SQTypeEmpty(SQType *q)
{
	int temp;
	temp = (q->tail == q->head);
	return (temp);
}

// FULL
int SQTypeFull(SQType *q)
{
	int temp;
	temp = (q->tail == QUEUELEN);
	return (temp);
}

// Clear
void SQTypeClear(SQType *q)
{
	q->tail = 0;
	q->head = 0;
}

// free
void SQTypeFree(SQType *q)
{
	if(q != NULL)
	{
		free(q);
	}
}

// In

int InSQType(SQType *q, DATA data)
{
	if(q->tail == QUEUELEN)
	{
		cout<<"Queue is full"<<endl;
		return (0);
	}
	else
	{
		q->data[q->tail++] = data;
		return (1);
	}
}

// out
DATA *QutSQType(SQType* q)
{
	if(q->head == q->tail)
	{
		cout<<"queue is empty!"<<endl;
		exit(0);
	}
	else
	{
		return &(q->data[q->head++]);
	}
}
// peek
DATA *PeekSQType(SQType *q)
{
	if(SQTypeEmpty(q))
	{
		cout<<"empty queue!"<<endl;
		return NULL;
	}
	else
	{
		return &(q->data[q->head]);
	}
}
// Length
int SQTypeLen(SQType *q)
{
	int temp;
	temp = q->tail - q->head;
	return temp;
}



int main(int argc, char* argv[])
{
	SQType * stack;
	DATA data;
	DATA *data1;

	stack = SQTypeInit();
	cout<<"In Queue"<<endl;
	cout<<"enter name age: "<<endl;

	do
	{
		cin>>data.name;
		cin>>data.age;

		if(strcmp(data.name, "0") == 0)
		{
			break;
		}
		else
		{
			InSQType(stack, data);
		}
	} while (1);

	data1 = PeekSQType(stack);
	cout<<data1->name<<data1->age<<endl;

	do
	{
		cout<<"Out queue: "<<endl;
		getchar();
		data1 = QutSQType(stack);
		cout<<data1->name<<data1->age<<endl;
	} while (1);


	SQTypeFree(stack);

	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值