数据结构 P62-62 算法实现 单链队列的创建及基本操作

来源:互联网 发布:网络教育大专要考试吗 编辑:程序博客网 时间:2024/05/16 17:00
#include<iostream>
using namespace std;
typedef  int QElemType;

 struct QNode              //创建节点结构体
{
QElemType data;
QNode     *next;
};
struct linkqueue         //创建链队列结构体
{
QNode *front;      //队头指针
QNode *rear;        //队尾指针
};

int InitQueue(linkqueue &Q)   //构造一个空队列
{
Q.front=Q.rear=new QNode();    
if(!Q.front) return 0;                               //存储分配失败
Q.front=NULL;
return 1;
}
int DestroyQueue(linkqueue &Q) //销毁队列
{
 while (Q.front)
 {
 Q.rear=Q.front->next;
 delete Q.front;
 Q.front=Q.rear;
 }
 return 1;
}
int EnQueue(linkqueue &Q,QElemType e) //插入元素e为Q的新的队尾元素
{
QNode *p;
p=new QNode();                                //创建一个节点用来储存元素e
if(!p) return 0;

p->data=e;                                      
p->next=NULL;

if (Q.front==NULL)                          //如果链队列为空 则把p作为队列的队头和队尾
Q.front=Q.rear=p;
else
{
Q.rear->next=p;                             //不为空则把p链接在队尾之后
Q.rear=Q.rear->next;
}
return 1;
}
int DeQueue(linkqueue &Q,QElemType &e)  //若队列不空,则删除Q的队头元素,用e返回其值
{
QNode *p;
if(!Q.front) return 0;
e=Q.front->data;
p=Q.front->next;
delete Q.front;
Q.front=p;
}
int main()
{
int e=2,x;
linkqueue Q;
InitQueue(Q);
EnQueue(Q,e);
DeQueue(Q,x);
cout<<x;
while (1){}
return 0;

}


————————————————————————————————————————————

/*单链队列的创建*/

#include<iostream>
using namespace std;
typedef  int QElemType;


 struct QNode              //创建节点结构体
{
QElemType data;
QNode     *next;
};
struct linkqueue         //创建链队列结构体
{
QNode *front;      //队头指针
QNode *rear;        //队尾指针
};

/*基本操作-初始化,销毁,插入,删除*/
int InitQueue(linkqueue &Q)   //构造一个空队列
{
Q.front=Q.rear=new QNode();    
if(!Q.front) return 0;                               //存储分配失败
Q.front=NULL;
return 1;
}
int DestroyQueue(linkqueue &Q) //销毁队列
{
 while (Q.front)
 {
 Q.rear=Q.front->next;
 delete Q.front;
 Q.front=Q.rear;
 }
 return 1;
}
int EnQueue(linkqueue &Q,QElemType e) //插入元素e为Q的新的队尾元素
{
QNode *p;
p=new QNode();                                //创建一个节点用来储存元素e
if(!p) return 0;


p->data=e;                                      
p->next=NULL;


if (Q.front==NULL)                          //如果链队列为空 则把p作为队列的队头和队尾
Q.front=Q.rear=p;
else
{
Q.rear->next=p;                             //不为空则把p链接在队尾之后
Q.rear=Q.rear->next;
}
return 1;
}
int DeQueue(linkqueue &Q,QElemType &e)  //若队列不空,则删除Q的队头元素,用e返回其值
{
QNode *p;
if(!Q.front) return 0;
e=Q.front->data;
p=Q.front->next;
delete Q.front;
Q.front=p;
}