顺序队列及其操作

问题:今天累了,没心情写,但我知道路漫漫,还是要坚持,要进步。顺序队列比较简单,明白原理就行。

        注:判断队列为空的条件:squeue->front==squeue->rear;

代码:

#include <iostream>

#include <cstdlib>

using namespace std;

#define MAXSIZE 20

typedef struct SQueue

{

	int data[MAXSIZE];

	int front;

	int rear;

}*SeqQueue;



void initSeqQueue(SeqQueue &squeue)   //初始化队列

{

	squeue=(SeqQueue)malloc(sizeof(struct SQueue));

	if(!squeue)

	{

		cout<<"allocate fail"<<endl;

		exit(-1);

	}

	else

	{

		squeue->front=squeue->rear=0;

	}

}



void enQueue(SeqQueue squeue,int elem)

{

	   if(squeue->rear==MAXSIZE)

	   {

		  cout<<"队列已满"<<endl;

		  exit(0);

	   }

	   else

	   {

		   squeue->data[squeue->rear]=elem;

		   squeue->rear++;

	   }

}



int deQueue(SeqQueue squeue)

{

	int elem;

	if(squeue->front==squeue->rear)

	{

		cout<<"队列已空"<<endl;

		exit(0);

	}

	elem=squeue->data[squeue->front];

	squeue->front++;

	return elem;

}



int main()

{

	SeqQueue squeue;

	int arr[8]={1,23,42,3,6,5,7,9};

	initSeqQueue(squeue);

	cout<<"入队:"<<endl;

	for(int i=0;i<8;i++)

	{

		enQueue(squeue,arr[i]);

	}

	cout<<"依次出队:"<<endl;

	while(squeue->front!=squeue->rear)

	{

		cout<<deQueue(squeue)<<"  ";

	}

	cout<<endl;

	return 0;

}

 

运行结果:

顺序队列及其操作

 

你可能感兴趣的:(队列)