當前位置:編程學習大全網 - 源碼下載 - c語言實現 壹個具有MaxLen個單元的環形隊列,設計求其中***有多少個元素

c語言實現 壹個具有MaxLen個單元的環形隊列,設計求其中***有多少個元素

#include<iostream.h>

#include<stdlib.h>

#define QElemType int

#define OVERFLOW -2

#define OK 1

#define ERROR 0

#define MAXQSIZE 100

typedef struct{

QElemType *base;

int front;

int rear;

int length;

int maxsize;

}SqQueue;

int InitQueue(SqQueue &Q,int n)

{

Q.base=new QElemType[n];

if(Q.base==0)return 0;

Q.rear=Q.front=0;

Q.length=0;

Q.maxsize=n;

return 1;

}//構造空隊列Q

int QueueLength (SqQueue Q){

return (Q.rear -Q.front +MAXQSIZE) % MAXQSIZE;

}//返回Q的元素個數,即隊列的長度

int EnQueue(SqQueue &Q,QElemType e)

{

if(Q.length==Q.maxsize)return 0;

Q.base[Q.rear]=e;

Q.rear=(Q.rear++)%Q.maxsize ;

Q.length++;

return 1;

}//插入元素e為Q的新的隊尾元素

int DeQueue(SqQueue &Q,QElemType &e)

{

if(Q.length==0)return 0;

e=Q.base[Q.front];

Q.front=(Q.front+1)%Q.maxsize;

Q.length--;

return 1;

}//刪除Q的隊頭元素,用e返回其值

int GetHead(SqQueue Q,QElemType &e)

{

if(Q.length==0)return 0;

e=Q.base[Q.front];

return 1;

}

bool Empty(SqQueue Q)

{

if(Q.length==0)return true;

return false;

}

void print(SqQueue Q)

{

int k=Q.front;

for(int i=1;i<=Q.length;i++)

{

cout<<Q.base[k]<<" ";

k=(k+1)%Q.maxsize;

}

cout<<endl;

}

void main()

{

SqQueue Q;

QElemType e,i;

InitQueue(Q,10);

cout<<"1:輸入壹隊列"<<endl;

cout<<"2:隊列的刪除"<<endl;

cout<<"3:隊列的插入"<<endl;

cout<<"4:返回元素個數"<<endl;

cout<<"5:退出"<<endl;

int s;

cin>>s;

while(s!=5){

switch (s){

case 1:

cout<<"輸入6個元素組成隊列: ";

for(i=0;i<6;i++)

{

cin>>e;

EnQueue (Q,e);

}

print(Q);

break;

case 2:

if(Empty(Q))

cout<<"要刪除的元素不存在";

else

{

GetHead( Q,e);

cout<<"要刪除的元素為 :"<<e<<endl;

DeQueue(Q,e);

cout<<"元素刪除後的隊列為: ";

print(Q);

}

break;

case 3:

cout<<"輸入準備插入的元素: ";

cin>>e;

EnQueue(Q,e);

cout<<"插入後的隊列為: ";

print(Q); break;

case 4:

cout<<"元素個數為:";

cout<<QueueLength ( Q);

cout<<endl; break;

case 5:

cout<<"退出程序";

//return;

default: cout<<"輸入錯誤,請重新輸入!"<<endl;

}

cout<<endl<<"請繼續選擇:"<<endl;

cin>>s;

}

}

  • 上一篇:《省道101穿越之旅》(壹)
  • 下一篇:如何用cmd畫愛心
  • copyright 2024編程學習大全網