您的位置:首页 > 其它

队列的线性存储和链式存储实现

2012-07-11 19:20 399 查看
队列是只允许在队尾插入元素,在队头删除元素的线性表。它有两种存储结构,即是顺序存储和链式存储结构。

链式存储结构实际上是一个同时带有首指针和尾指针的单链表。实现如下:

#include<iostream>
using namespace std;
const int MaxSize=20;

typedef struct
{
int data[MaxSize];
int font,rear;
}SqQueue;

void InitQueue(SqQueue &sq)
{
sq.rear=sq.font=0;
}

int EnQueue(SqQueue &sq,int x)//入队
{
if((sq.rear+1)%MaxSize==sq.font)
return 0;
else
{
sq.data[sq.rear]=x;
sq.rear=(sq.rear+1)%MaxSize;//队头循环加1

return 1;
}
}
int DeQueue(SqQueue &sq,int &x) //出队列,将值保存在x当中
{
if(sq.rear==sq.font)//队列为空
return 0;
else
{

x=sq.data[sq.font];
sq.font=(sq.font+1)%MaxSize;
return 1;
}
}

int IsEmpty(SqQueue &sq) //判断队列是否为空
{
if(sq.rear==sq.font)
return 1;
else
return 0;

}

int GetHead(SqQueue sq,int &x) //取队头元素
{
if(sq.rear==sq.font)//队列为空
return 0;
else
x=sq.data[(sq.font+1)%MaxSize];
return 1;

}

/*链式队列*/
typedef struct node
{
int data;
struct node *next;
}SNode;

typedef struct
{
SNode *font,*rear;
}LQueue;

void InitQueue(LQueue * &lq)
{
lq=(LQueue *)malloc(sizeof(LQueue));
lq->font=lq->rear=NULL;//初始情况
}

void EnQueue(LQueue * &lq,int x)
{
SNode *s;
s=(SNode *)malloc(sizeof(SNode));
s->data=x;
s->next=NULL;//新节点的初始化
if(lq->font==NULL&&lq->rear==NULL) //若原来队列为空
{
lq->font=s;
lq->rear=s;

}
else
{
lq->rear->next=s;
lq->rear=s;  //将s插入到队列尾部
}
}

int DeQueue(LQueue *&lq,int &x)
{
SNode *p;
if(lq->font==NULL)
return 0;
else
{
x=lq->font->data;
p=lq->font;//保存要删除的结点
if(lq->font==lq->rear) //判断是否只有一个节点
{
lq->font=lq->rear=NULL;
}
else
lq->font=lq->font->next;
}
free(p);
return 1;
}
int QueueEmpty(LQueue *&lq)//判断队列是否为空
{
if(lq->font==NULL&&lq->rear==NULL)
return 1;
else
return 0;

}
void main()
{
SqQueue sq;
int x;
InitQueue(sq);

for(int i=0;i<10;i++)
{
EnQueue(sq,i);
cout<<i<<" ";
}
cout<<endl;

for(int j=0;j<10;j++)
{
DeQueue(sq,x);
cout<<x<<" ";
}
cout<<endl;
cout<<"/***********链式队列**************/"<<endl;
LQueue *lq;

InitQueue(lq);

for(int i=0;i<20;i++)
{
EnQueue(lq,i);
cout<<i<<" ";
}
cout<<endl;

for(int j=0;j<20;j++)
{
DeQueue(lq,x);
cout<<x<<" ";
}

}


复制搜索

复制搜索
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: