链式队列:
#include <iostream>
#include <stdio.h>
#include <malloc.h>
const int MAXSIZE=100;
typedef int ElemType;
using namespace std;
typedef struct qnode{
ElemType data;
struct qnode *next;
}DataNode;
typedef struct{
DataNode *front;
DataNode *rear;
}LinkQuNode;
void InitQueue(LinkQuNode * &q){
q=(LinkQuNode*)malloc(sizeof(LinkQuNode));
q->front=q->front=NULL;
}
void DestroyQueue(LinkQuNode * &q){
DataNode *pre=q->front,*p;
if(pre!=NULL)
{
p=pre->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=pre->next;
}
}
free(pre);
}
bool IsEmpty(LinkQuNode *& q){
return q->front==NULL;
}
void Enqueue(LinkQuNode *q,ElemType &e){
DataNode *p;
p=(DataNode*)malloc(sizeof(DataNode));
p->data=e;
p->next=NULL;
if(q->rear==NULL)
q->front=q->rear=p;
else
{
q->rear->next=p;
q->rear=p;
}
}
bool Dequeue(LinkQuNode *q,ElemType &e){
DataNode *m;
if(q->rear==NULL)
return false ;
m=q->front;
if(q->front==q->rear)
q->front=q->rear=NULL;
else
{
q->front=q->front->next;
}
e=m->data;
free(m);
return true;
}
int main(){
LinkQuNode *q;
InitQueue(q);
int i=10;
ElemType e;
while(i--)
{
Enqueue(q,i);
}
Dequeue(q,e);
cout<<"出队的元素为:"<<e<<endl;
Dequeue(q,e);
cout<<"出队的元素为:"<<e<<endl;
Dequeue(q,e);
cout<<"出队的元素为:"<<e<<endl;
// while(!IsEmpty)
// {
// Dequeue(q,e);
// cout<<"出队的元素顺序为: "<<e<<endl;
// }
DestroyQueue(q);
return 0;
}
顺序队列:
#include <iostream>
#include <malloc.h>
const int MAXSIZE=100;
typedef int ElemType;
using namespace std;
typedef struct{
ElemType data[MAXSIZE];
int front,rear;
}SqQueue;
void InitQueue(SqQueue *&q)
{
q=(SqQueue *)malloc(sizeof(SqQueue));
q->front=-1;
q->rear=-1;
}
void DestroyQueue(SqQueue *&q)
{
free(q);
}
bool QueueEmpty(SqQueue *&q)
{
return q->front==q->rear;
}
bool EnQueue(SqQueue *&q,ElemType e)
{
if(q->rear+1%MAXSIZE==q->front)
return false;
else
{
q->rear=q->rear+1%MAXSIZE;
q->data[q->rear]=e;
return true;
}
}
bool DeQueue(SqQueue *&q,ElemType &e)
{
if(q->front==q->rear)
return false;
else
{
q->front=(q->front+1)%MAXSIZE;
e=q->data[q->front];
return true;
}
}
void test01(SqQueue *&q){
ElemType k=10;
while(k--)
EnQueue(q,k);
for(int i=q->front+1;i<=q->rear;i++)
cout<<q->data[i]<<endl;
k=3;
ElemType e;
while(k--)
{
DeQueue(q,e);
cout<<"出队的元素为:"<<e<<endl;
}
cout<<"队中剩下的元素为:"<<endl;
for(int i=q->front+1;i<=q->rear;i++)
cout<<q->data[i]<<endl;
DestroyQueue(q);
}
int main()
{
SqQueue *q;
ElemType e;
ElemType a[10]={1,2,3,4,5,6,7,8,9,10};
InitQueue(q);
test01(q);
}