数据结构习题——9循环队列

time_limit

3000MS

memory_limit

10000KB

description

假设将循环队列定义为:以域变量rear和length分别指示循环队列中队尾元素的位置和内含元素的个数。编写相应的入队列和出队列的程序,并判断循环队列是否队满(在出队列的算法中要返回队头元素)。

input

假设队列数组为Queue[MAXSIZE],第一行输入队列大小N,第二行开始输入若干入队元素,队满时,停止入队。第三行输入出队元素。

output

输出入队出队操作后的循环队列,并返回出队元素的队头元素。

sample_input

5

3 4 6 2 7

4

sample_output

6 2 7

6

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
#define Initsize 500
using namespace std;
typedef int Elemtype;
typedef struct {
	Elemtype *base;
	int Front;
	int rear;
	int length;
}Quene, *PQuene;

PQuene Init_quene()
{
	PQuene p;
	p = (PQuene)malloc(sizeof(Quene));
	p->base = (Elemtype *)malloc(sizeof(Elemtype)*Initsize);
	if (p == NULL) { printf("Error Init"); return p; }
	p->length = p->Front = 0;
	p->rear = 0;
	return p;
}

void enQuene(PQuene p, Elemtype x,int Size)
{
	if ((p->rear ) % Size == p->Front&&p->length!=0) { printf("Error enQuene"); return; }  //if length==Size
	if(p->rear==-1)p->rear=0;
	p->base[p->rear] = x;
	p->rear = (p->rear + 1) % Size;
	p->length++;
}

Elemtype deQuene(PQuene p,int Size)
{
	Elemtype x;
	x = p->base[p->Front];
	p->Front = (p->Front + 1) % Size;
	p->length--;
	return x;
}

int isfull(PQuene p,int Size)
{
	return (p->length == Size);
}

int isnull(PQuene p)
{
    return (p->length==0);
}

int show(PQuene p,int Size)
{
	int i;
	if(isnull(p))return -1;     //队列空退出
	i = p->Front;  //先输出一个,免得队列满的时候,下面判断出错
	printf("%d ", p->base[i]);
	i=(i+1)%Size;
	while (i != (p->rear)%Size) {
		printf("%d ", p->base[i]);
		i = (i + 1) % Size;
	}

	printf("\n");
	return 0;
}

int showtop(PQuene p)
{
	if(isnull(p))return -1;
	printf("%d\n", p->base[p->Front]);
	return 0;
}
int main()
{
	int i = 0, out, flag = 0,Size;
	int data = 0;
	char s[100],c;

	PQuene pquene;
	scanf("%d", &Size);
	pquene = Init_quene();
	getchar();
	gets(s);
	while (s[i] != '\0') {          //将字符串中的内容存入队列
		if (s[i] == ' '&&flag == 1) {
			enQuene(pquene, data,Size);
			data = 0;
			i++;
			flag = 0;
			continue;
		}
		flag = 1;
		c = s[i++];
		data = data * 10 + (c - 48);
	}
	enQuene(pquene, data,Size);
    char zf[50];
    gets(zf);
	scanf("%d", &out);

	while (deQuene(pquene,Size) != out);
	show(pquene,Size);
	showtop(pquene);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41858784/article/details/82181001