本文将继续梳理数据结构常考代码,这篇文章将介绍队列相关操作及算法
队列的基本操作不难,这里仅展示代码,不再做过多的讲解
一、链队列(98-99页)
1.类型定义
typedef struct node
{
int data;
struct node *next;
}node;
typedef struct
{
node *front;//队头
node *rear;//队尾
}linkquene;
2.初始化
void init(linkquene *a)
{
a->front=(node*)malloc(sizeof(node));
a->rear=a->front;
a->front->next=NULL;
}
3.入队
void enter(linkquene *a,int n)
{
node *p;
p=(node*)malloc(sizeof(node));
p->data=n;
a->rear->next=p;
a->rear=p;
}
4.出队
int del(linkquene a)
{
int n=q->front;
node *x;
x=q->front->next;
q->front->next=p->next;
free(x);
return n;
}
二、循环队列(101-102页)
1.类型定义
typedef struct
{
int arr[50];
int front;
int rear;
}seqquene;
2.初始化
void init(seqquene *a)
{
a->front=a->rear=0;
}
3.入队出队:这些操作都比较简单,书上写的也是比较详细了,不再赘述,注意修改指针的语句需要对队列最大长度取余
4.注意事项:
判断队空:frontrear
判断队满:(front+1)%maxsizerear
三、经典算法:打印杨辉三角
#include <iostream>
using namespace std;
typedef struct
{
int arr[50];
int front;
int rear;
}seqquene;
void init(seqquene *a)
{
a->front=a->rear=0;
}
void enter(seqquene *q,int x)
{
q->arr[q->rear]=x;
q->rear=(q->rear+1)%50;
}
int del(seqquene *q)
{
int n=q->arr[q->front];
q->front=(q->front+1)%50;
return n;
}
void yhsj(int n)
{
seqquene q;
init(&q);
enter(&q,1);//第一行元素入队
int i,j,x,temp=0;
for(i=2;i<=n;i++)//利用n-1行元素生成第n行的元素
{
enter(&q,1);//第一个元素入队
for(j=1;j<=i-2;j++)//生成中间n-2个元素
{
temp=del(&q);//先出队,再打印,利用此元素和其下一个元素(此时下一个还在队列中)生成下一行待打印的元素
cout<<temp<<" ";
x=q.arr[q.front];//gethead函数
temp=temp+x;
enter(&q,temp);
}
x=del(&q);
cout<<x<<" "<<endl;
enter(&q,1);
}
while(q.front!=q.rear)//打印最后1行的元素
{
cout<<del(&q)<<" ";
}
}
int main()
{
int n;
cin>>n;
yhsj(n);
return 0;
}
本代码根据书上的代码改编而来,略作调整,书上的注释还是挺详细的,所以看我的文章和课本搭配食用更佳
本文完,欢迎评论区探讨交流