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;
}