顺序队的实现

#include<assert.h>
#define MAXQSIZE 100

//入队的一端叫队尾,出队的一端叫队头
//难点1:如何将队列的入队以及出队时间复杂度都降低为O(1)?
//难点2:怎么将判空和判满操作区分开
typedef int ElemType;
typedef struct queue
{
	ElemType*data;
	int front;//一直指向第一个节点
	int rear;//一直指向最后一个节点
}Queue,*PQueue;

void Init_Queue(PQueue pq);
bool Push(PQueue pq, ElemType val);
bool Pop(PQueue pq, ElemType* rtval);
bool Top(PQueue pq, ElemType* rtval);
int Get_length(	PQueue pq);
bool IsEmpty(PQueue pq);
bool IsFull(PQueue pq);
void Clear(PQueue pq);
void Destory(PQueue pq);
void Show(PQueue pq);
#include<stdio.h>
#include<stdlib.h>

#include<string.h>
#include"queue.h"


void Init_Queue(PQueue pq)
{
	assert(pq!= NULL);
	pq->data = (ElemType*)malloc(sizeof(ElemType*) * MAXQSIZE);
	assert(pq->data != NULL);
	pq->front = 0;
	pq->rear = 0;
}

bool Push(PQueue pq, ElemType val)
{
	assert(pq != NULL);
	if (IsFull(pq))
		return false;
	pq->data[pq->rear] = val;
	pq->rear = (pq->rear + 1) % MAXQSIZE;
	return true;
}


bool Pop(PQueue pq, ElemType* rtval)
{
	assert(pq != NULL);
	if (IsEmpty(pq))
		return false;
	*rtval = pq->data[pq->front];
	pq->front = (pq->front + 1) % MAXQSIZE;
	return true;
}

bool Top(PQueue pq, ElemType* rtval)
{
	if (IsEmpty(pq))return false;
	*rtval = pq->data[pq->front];
	return true;
}

int Get_length(PQueue pq)
{
	//assert

	int length = (pq->rear - pq->front + MAXQSIZE) % MAXQSIZE;
	return length;
}
bool IsEmpty(PQueue pq)
{
	return pq->front == pq->rear;
}

bool IsFull(PQueue pq)
{
	return (pq->rear + 1) % MAXQSIZE == pq->front;
}



void Clear(PQueue pq)
{
	pq->rear = 0;
	pq->front = 0;
}

void Destory(PQueue pq)
{
	free(pq->data);
	pq->data = NULL;
	pq->front = pq->rear = 0;
}


void Show(PQueue pq)
{
	for (int i=pq->front;i!=pq->rear;i=(i+1)%MAXQSIZE)
	{
		printf("%d ", pq->data[i]);
	}
	printf("\n");
}

int main()
{
	Queue qu;
	Init_Queue(&qu);
	for (int i= 0; i < 10; i++)
	{
		Push(&qu, i + 1);
	}
	Show(&qu);
	int tmp;
	Top(&qu,&tmp);
	printf("%d\n",tmp);
    Show(&qu);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值