1.初始化顺序循环队列:判空;
2. 新元素入队;
3. 元素出队;
4.显示队列中所有元素的值及位置。
5.以上功能各用一个子函数实现,并编写出相应的主函数。
using namespace std;
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#define Maxsize 20
/*
顺序队列的要素:
队列是队尾进入元素,对头删除元素
初始化时,rear=front=-1
元素进队时,front+1
元素出队时,rear+1
当rear= Maxsize-1,front=-1时, 队列全部进队
当rear=front= Maxsize-1时,队列已经全部出队
*/
/*
循环队列的要素:
front = rear ,则表示为队列为空
(rear+1)%Maxsize = front ,则表示队列为满
进队:s->rear = (s->rear + 1) % Maxsize;
出队:s->front = (s->front + 1) % Maxsize;
*/
struct Sqqueue
{
char data[Maxsize];
int front; //指向队头
int rear; //指向对尾
};
//初始化一个新的队列
void InitSqqueue(Sqqueue *&s)
{
s = new Sqqueue;
s->front = s->rear = 0;
}
//销毁队列
void DestorySqqueue(Sqqueue *&s)
{
free(s);
}
int LengthSqqueue(Sqqueue *&s)
{
return s->rear - s->front;
}
//进队列
bool InSqqueue(Sqqueue *& s, char &data)
{
if (s->rear == Maxsize - 1)
{
return false;
}
s->data[s->rear] = data;
s->rear = (s->rear + 1) % Maxsize;
return true;
}
//出队列
bool OutSqqueue(Sqqueue *&s, char &data)
{
if (s->front == s->rear)
{
return false;
}
data = s->data[s->front];
s->front = (s->front + 1) % Maxsize;
return true;
}
//判断循环队列是否为空
void IsemptySqqueue(Sqqueue *& s)
{
if (s->front == s->rear)
{
cout << "循环队列为空" << endl;
}
}
void PrintSqqueue(Sqqueue *& s)
{
for (int i = 0; i < LengthSqqueue(s); i++)
{
cout << "在循环队列中的位置为:"<<i<<"该字符为"<<s->data[i]<<endl;
}
}
int main()
{
char InData;
char OutData;
int size;
Sqqueue * s;
InitSqqueue(s);
IsemptySqqueue(s);
cout << "需要输入队列字符的个数" << endl;
cin >> size;
for (int i = 0; i < size; i++)
{
cout << "输入进队列的字符" << endl;
cin >> InData;
InSqqueue(s, InData);
}
PrintSqqueue(s);
cout << endl;
OutSqqueue(s, OutData);
cout << "从队列中删除的字符为:" << OutData<< endl;
PrintSqqueue(s);
cout << endl;
system("pause");
return 0;
}