1. 程式人生 > >C++編寫利用資料結構中佇列(Queue)打印出使用者所指定長度的楊輝三角

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();
}