顺序队列C/C++实现

时间:2024-08-21 08:03:31
#include <iostream>
using namespace std; const int MAXSIZE = 1000;
typedef int ELEMTYPE;
const int N = 10;
typedef struct {
ELEMTYPE data[MAXSIZE];
int head;
int tail;
}Queue; Queue Q;
void initQueue(Queue &Q);
void printQueue(Queue &Q);
int isQueueEmpty(Queue &Q);
int isQueueFull(Queue &Q);
int EnQueue(Queue &Q,ELEMTYPE e);
int DeQueue(Queue &Q,ELEMTYPE &e); int main()
{ for(int i=0;i<N;i++)
{
EnQueue(Q,i);
}
printQueue(Q);
return 0;
} void initQueue(Queue &Q)
{ Q.head = 0;
Q.tail = 0;
}
void printQueue(Queue &Q)
{
ELEMTYPE e;
while(!isQueueEmpty(Q))
{
DeQueue(Q,e);
cout<<e<<"\t";
}
}
int isQueueEmpty(Queue &Q)
{
return Q.head==Q.tail;
} int isQueueFull(Queue &Q)
{
return (Q.tail+1)%MAXSIZE == Q.head;
} int EnQueue(Queue &Q,ELEMTYPE e)
{ if(isQueueFull(Q)) return 0;
Q.tail = (Q.tail+1)%MAXSIZE;
Q.data[Q.tail] = e;
return 1;
}
int DeQueue(Queue &Q,ELEMTYPE &e)
{
if(isQueueEmpty(Q)) return 0;
Q.head = (Q.head+1)%MAXSIZE;
e = Q.data[Q.head];
return 1;
}

**注意顺序队列的初始化可以让Q.head=Q.tail=0,也可以Q.head=Q.tail=1;

前者相当于带头结点的链队列;后者相当于不带头结点的链队列**