c++ 数据结构 用循环队列实现杨辉三角形的打印

1.循环队列

(1)功能:

# include<iostream>
using namespace std;
# include<assert.h>
class SeqQueue{
private:
	int* elements;              //存放队列元素的数组
	int rear,front;           //队尾指针和对头指针
	int maxSize;              //队列可容纳的最大元素个数
public:
	SeqQueue(int sz=10);          //构造函数
	~ SeqQueue(){ delete[]elements;}    //析构函数
	bool EnQueue(const int x);         //进队函数
	bool DeQueue(int& x);               //出队函数
	bool getFront(int& x);             //取队头元素
    bool isEmpty(){return (front==rear)?true:false;}    //判断队空
	bool isFull(){return ((rear+1)%maxSize==front)?true:false;}    //判断队满
};


(2)具体实现:

# include"SeqQueue.h"
# include<iostream>
using namespace std;
SeqQueue::SeqQueue(int sz):rear(0),front(0),maxSize(sz){
	elements=new int[maxSize];
	assert(elements!=NULL); //断言机制:如果不满足括号内条件将终止程序的执行
}
bool SeqQueue::EnQueue(const int x){
	if(isFull()) return false;
	else 
		elements[rear]=x;
	    rear=(rear+1)%maxSize; //加一再取余是为了rear指向队列最后一个元素(下标maxSize-1),再进一下标就到了0
	return true;
}
bool SeqQueue::DeQueue(int& x){
	if(isEmpty()) return false;
	else
		x=elements[front];
	    front=(front+1)%maxSize;
	return true;
}
bool SeqQueue::getFront(int& x){
	if(isEmpty())  return false;
	else
		x=elements[front];
	return true;
}
2.打印函数:

# include"SeqQueue.h"
# include<iostream>
using namespace std;
void YANGVI(int n){
	int j,k;
	int s=0,t,sum;
	SeqQueue Q(n+3); 
	Q.EnQueue(1);
	Q.EnQueue(1);
	for(j=1;j<=n;j++){       //循环n次
		cout<<endl;
		Q.EnQueue(0);
        for(k=1;k<=j+2;k++){     //输出第n行的n+1个元素
		    Q.getFront(t);
		    sum=s+t;
		    Q.EnQueue(sum);
                    Q.DeQueue(s);
		    if(k!=j+2)
		      cout<<s<<" ";
		}
	}
}


3.主函数:

# include"YANGVI.h"
# include<iostream>
using namespace std;
int main(){
	int n;
	cout<<"please put in the line number:"<<endl;
	cin>>n;
	YANGVI(n);
	system("pause");
    return 0;
}



  • 6
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值