在学习数据结构队列基本操作的时候,书上的都是伪码且限提供算法思想。能够看懂并实现书上的代码没必要往下看了。
写这篇文章的目的是将自己对队列基本操作做个总结,也给那些正在学习数据结构的人提供点便利。欢迎一起来学习数据结构与算法。
源代码如下(实现队列构建,读入,判空,删除,添加。。。。)
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct student
{
int data; //定义结构体节点
struct student * next;
}node;
typedef struct linkqueue
{
node *first;
node *rear; //定义队列结构,首指针和尾指针
}queue;
//功能:初始化 把队首和队尾指针置空
void Initqueue(queue &HQ)
{
HQ.first=HQ.rear=NULL;
}
//函数功能:向队列中添加一个新元素,在尾节点之后
queue insert(queue &HQ,int x)
{
node *s;
s = new node;
s->data=x;
s->next=NULL;
if(HQ.rear==NULL)
{
HQ.first = s;
HQ.rear = s;
}
else
{
HQ.rear->next=s;
HQ.rear=s;
}
return HQ;
}
//功能:从队列中删除一个元素
int delqueue(queue &HQ)
{
node *p;
int temp;
//若链队为空则停止运行
if(HQ.first==NULL)
{
printf("队列为空,无法删除! ");
exit(1);
}
temp=HQ.first->data;
//暂存队首元素以便返回
p=HQ.first;
//暂存队首指针以便回收队尾结点
HQ.first=p->next; //使队首指针指向下一个结点
//若删除后链队为空,则需同时使队尾指针为空
if(HQ.first==NULL)
{
HQ.rear=NULL;
}
free(p); //回收原队首结点
return temp; //返回被删除的队首元素值
}
//功能:读取队首元素
int readqueue(queue &HQ)
{ /*若链队为空则停止运行*/
if(HQ.first==NULL)
{
cout<<"队列为空,无法删除! ";
exit(1);
}
return HQ.first->data; //返回队首元素
}
//功能:检查链队是否为空,若为空则返回1,否则返回0
int emptyqueue(queue HQ)
{
//判断队首或队尾任一个指针是否为空即可
if(HQ.first==NULL)
{
return 1;
}
else
{
return 0;
}
}
//功能:清除链队中的所有元素
void clearqueue(queue &HQ)
{
node *p=HQ.first; //队首指针赋给p
while(p!=NULL)
{
free(p);
p = p->next;
}
//循环结束后队首指针已经为空
HQ.rear=NULL; //置队尾指针为空
}
//功能:输出链队中的所有元素
void readall(queue &HQ)
{
node *p=HQ.first;
while (p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
int main()
{
queue q;
int a[]={1,8,9,2,6,65};
int i;
Initqueue(q);
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
insert(q,a[i]);
}
cout<<endl<<"读取队列中全部的数据:\n";
readall(q);
cout<<"插入一个元素 —100"<<endl;
insert(q,100); //插入一个数据
cout<<"插入后全部元素为:"<<endl;
readall(q);
cout<<"读取的队首节点:"<<readqueue(q)<<endl;
cout<<endl;
while(!emptyqueue(q)) //判空
{
cout<<"删除的节点:"<<delqueue(q)<<endl;;
cout<<"剩下的节点"<<endl;
readall(q);
}
clearqueue(q);
return 0;
}