c_cpp 使用数组实现线性队列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用数组实现线性队列相关的知识,希望对你有一定的参考价值。
#include <bits/stdc++.h>
#define MAX_SIZE 10
using namespace std;
// #Queue #BasicProblem
//Slots of array are reused in this procedure
bool isFull(int frontIndex,int backIndex){
if(backIndex-frontIndex+1==MAX_SIZE){ //size of array is (last_i-first_i)+1
return true;
}else{
return false;
}
}
bool isEmpty(int frontIndex,int backIndex){
if(backIndex-frontIndex+1==0){
return true;
}else{
return false;
}
}
bool Enq(int Q[],int push,int &frontIndex,int &backIndex){
if(isFull(frontIndex,backIndex)==true){
return false;
}else{
backIndex++;
Q[backIndex]=push;
return true;
}
}
bool Deq(int Q[],int &frontIndex,int &backIndex,int &removed){
if(isEmpty(frontIndex,backIndex)==true){
return false;
}else{
removed=Q[frontIndex];
for(int i=frontIndex;i<backIndex;i++){
Q[i]=Q[i+1]; //moving elements to the left
}
backIndex--; // fot the left shift
return true;
}
}
int main() {
cout<<"Instructions: \n";
cout<<"Type add to Enqueue"<<endl;
cout<<"Type del to Dequeue"<<endl;
cout<<"Type front to check front element"<<endl;
cout<<"Type exit to stop using the Queue"<<endl;
int Q[MAX_SIZE];
int frontIndex=0; //front index always stays 0 as the elements are all moved left for every dequeue
//so is this variable necessary?
int backIndex=-1; // initializing an empty Queue
int removed; // variable to access the element dequeued
while(1){
string instruction;
cout<<"Instruction: ";
cin>>instruction;
if(instruction=="exit"){
break;
}else if(instruction=="add"){
cout<<"Enter the element top be enqueued"<<endl;
int push; //element to be enqueued
cin>>push;
if(Enq(Q,push,frontIndex,backIndex)==true){
cout<<"Element "<<Q[backIndex]<<" successfully enqueued"<<endl;
}else{
cout<<"ERROR: Queue is already full!"<<endl;
}
}else if(instruction=="del"){
if(Deq(Q,frontIndex,backIndex,removed)==true){
cout<<"Element "<<removed<<" successfully Dequeued"<<endl;
if(isEmpty(frontIndex,backIndex)==false){
cout<<"Front Element is:"<<Q[frontIndex]<<endl;
}else{
cout<<"Queue is now Empty!"<<endl;
}
}else{
cout<<"ERROR : Queue is empty!"<<endl;
}
}else if(instruction=="front"){
if(isEmpty(frontIndex,backIndex)==false){
cout<<"Front Element is:"<<Q[frontIndex]<<endl;
}else{
cout<<"Queue is now Empty!"<<endl;
}
}else{
cout<<"ERROR : Unknown operation! Please try again"<<endl;
}
}
return 0;
}
以上是关于c_cpp 使用数组实现线性队列的主要内容,如果未能解决你的问题,请参考以下文章