C++编写利用数据结构中队列(Queue)打印出用户所指定长度的杨辉三角

#include <iostream>
#include <assert.h>
using namespace std;
class Yanghui{
public:
 class Node{
 public:
  Node():data(0){
  next=NULL;
  }
  Node(int x):data(x){
  next=NULL;
  }
 public:
  int data;
  Node *next;
 };
public:
 class Queue{
 public:
  Queue(){
  head=tail=NULL;
  }
  bool isEmpty(){
   return head==NULL&&tail==NULL;
  }
  void Push(Node *node){
   if(isEmpty()){
    head=tail=node;
    return;
   }
   tail->next=node;
   tail=node;
  }
  Node *Pop(){
   assert(!isEmpty());
   Node *temp;
   temp=head;
   if(head==tail){
    head=tail=NULL;
    return temp;
   }
   head=head->next;
   return temp;
  }
 public:
  Node *head;
  Node *tail;
 };
public:
 Yanghui(){}
 Yanghui(int x):depth(x){}
 void Set(int x){
  depth=x;
 }
 void Init();
 void PrintYanghui();
public:
 int depth;
 Queue yang;
};
void Yanghui::Init(){
 cout<<"Input the depth:"<<endl;
 cin>>depth;
}
void Yanghui::PrintYanghui(){
 yang.Push(new Yanghui::Node(1));
 int origin=0;
 Yanghui::Node *popnode;
 for(int i=0;i<depth;++i){
  yang.Push(new Yanghui::Node(0));
  for(int j=0;j<i+2;++j){
   popnode=yang.Pop();
   yang.Push(new Yanghui::Node(origin+popnode->data));
   origin=popnode->data;
   //if(j==i+2)break;
   if(!popnode->data)break;
   cout<<popnode->data<<'\t';
  }
  cout<<endl;
 }
}
void main(){
 Yanghui obj;
 obj.Init();
 obj.PrintYanghui();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值