顺序队列

//SeqQueue.h

#ifndef _SEQQUEUE_H_
#define _SEQQUEUE_H_

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

#define MAXSIZE 10
#define INCREASE 6

typedef int ElementType;

typedef struct SeqQueue
{
	ElementType *base;
	int head;			//队头指针
	int tail;			//队列尾后指针
	int capacity;
}SeqQueue;

bool InitSeqQueue(SeqQueue *sq);
bool increase(SeqQueue *st);
bool EnSeqQueue(SeqQueue *sq, ElementType e);
void ShowSeqQueue(SeqQueue sq);
bool DeSeqQueue(SeqQueue *sq);
int length(SeqQueue sq);
bool IsFull(SeqQueue sq);
bool IsEmpty(SeqQueue sq);
bool GetTop(SeqQueue sq, ElementType *e);
void Clear(SeqQueue *sq);
void Destroy(SeqQueue *sq);


#endif //_SEQQUEUE_H_



//SeqQueue.c

#include "SeqQueue.h"

bool InitSeqQueue(SeqQueue *sq)
{
	ElementType *p = (ElementType *)malloc(MAXSIZE * sizeof(ElementType));
	if( NULL == p )
		return false;

	sq->base = p;
	sq->head = sq->tail = 0;
	sq->capacity = MAXSIZE;

	return true;
}

bool increase(SeqQueue *sq)
{
	ElementType *newBase = (ElementType *)realloc(sq->base, sizeof(ElementType) * (MAXSIZE + INCREASE));
	if (NULL == newBase)
		return false;

	sq->base = newBase;
	//两指针不变
	sq->capacity += INCREASE;

	return true;
}

bool EnSeqQueue(SeqQueue *sq, ElementType e)
{
	if( IsFull(*sq) && !increase(sq) )
	{
		printf("队列已满\n");
		return false;
	}

	sq->base[sq->tail++] = e;
	return true;
}

void ShowSeqQueue(SeqQueue sq)
{
	for (int i = sq.head; i != sq.tail; i++)
	{
		printf("%d\n", sq.base[i]);
	}
}

bool DeSeqQueue(SeqQueue *sq)
{
	if( IsEmpty(*sq) )
	{
		printf("队列为空\n");
		return false;
	}

	sq->head++;

	return true;
}

int length(SeqQueue sq)
{
	return sq.tail - sq.head;
}

bool IsFull(SeqQueue sq)
{
	return sq.capacity <= sq.tail;
}

bool IsEmpty(SeqQueue sq)
{
	return sq.head == sq.tail;
}

bool GetTop(SeqQueue sq, ElementType *e)
{
	if( IsEmpty(sq) )
	{
		printf("队列为空\n");
		return false;
	}

	*e = sq.base[sq.head];
	return true;
}

void Clear(SeqQueue *sq)
{
	sq->head = sq->tail = 0;
}

void Destroy(SeqQueue *sq)
{
	free(sq->base);
	sq->base = NULL;
	sq->head = sq->tail = 0;
	sq->capacity = 0;
}



//main.c

#include "SeqQueue.h"

void main()
{

	SeqQueue sq;
	ElementType e;
	InitSeqQueue(&sq);

	for(int i = 0; i != 15; i++)
		EnSeqQueue(&sq, i);

	printf("显示\n");
	ShowSeqQueue(sq);

	if( GetTop(sq, &e) )
		printf("队头元素为%d\n", e);

	printf("出队\n");
	for (int i = 0; i != 5; i++)
		DeSeqQueue(&sq);

	printf("显示\n");
	ShowSeqQueue(sq);

	printf("队列长度为%d\n", length(sq));

	if (GetTop(sq, &e))
		printf("队头元素为%d\n", e);

	printf("清除\n");
	Clear(&sq);
	printf("显示\n");
	ShowSeqQueue(sq);

	Destroy(&sq);

	system("pause");
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值