liyuxia713

蹒跚前行者

常用链接

统计

Algorithms

C++

最新评论

[导入]用循环队列输出杨辉三角形

用循环队列输出杨辉三角形貌似有点小题大做,但主要是为了练习队列应用嘛。说实在这个小程序也让我调试了很长时间.

用这个程序用户就可以自行输入想要的杨辉三角形的行数了。

//YHTriangle.cpp
//输出杨辉三角形
//算法思想:首先在循环队列中存放第三行的 1,2,1和第四行的1.
//若循环队列队头元素和队头第二个元素均为1,则从队头删除一个1,在队尾插入两个1.
//若不然,将队对头元素和队头第二个元素相加,将和值插入到队尾,删除对头一个元素。
//若想输出杨辉三角形n行,将循环队列长度设置成 n+2。
//输出:前两行直接输出。定义了print函数控制后面每行输出的元素个数
#include "Queue.h"
#include "CycQueue.h"
#include <iostream>
using namespace std;

//输出n个空格
void print_space(int n);
//n行杨辉三角形的输出格式
void print(int k, int n);

int main()
{
    int n;
    cout << "Please enter the YangHui Triangle row number n:";
    cin >> n;

    CycQueue<int> YHTri(n+2);

    YHTri.push(1);
    YHTri.push(2);
    YHTri.push(1);
    YHTri.push(1);
   //输出前两行
    print(1,n);
    print(1,n);
    print(1,n);
    while( !YHTri.full())
    {
        int a,b;
        //若队头元素和队头第二个元素均为1
        if( (YHTri.top() == 1) && (YHTri.second() == 1))
        {
            a = YHTri.pop_top();
            YHTri.push(1);
            YHTri.push(1);
            print(a,n);
        }
        //若不然
        else
        {       
            a = YHTri.pop_top();
            b = YHTri.top();
            YHTri.push(a + b);
            print(a,n);           
        }
    }

    //输出循环队列中留存的元素
    while( !YHTri.empty())
    {
        print(YHTri.pop_top(),n);
    }

    system("pause");
    return 0;
}

void print_space(int n) //输出n个空格
{
    while(n--) cout << " ";
}

int i = 1, j = 0;
void print(int k, int n) //n行杨辉三角形的输出格式
{
    if( i==1 ) print_space(n);
    if(j++ != i) ;
    else
    {
        cout << endl;
        print_space(n-i);
        ++i;
        j = 1;
    }
    cout << k <<" ";
}

//循环队列的模板类声明

#ifndef CYCQUEUE_H
#define CYCQUEUE_H

#include <iostream>
using namespace std;

template<class T>
class CycQueue:public Queue<T>
{
public:
    CycQueue(int maxsz = 100):len(maxsz)
    {
        elems = new T[maxsz];
        front = rear = 0;
    };
    ~CycQueue(){delete[] elems;    };

    void clear() {rear = front = 0;};
    int size()const
    bool full()const
    bool empty()const
    bool push(const T& item);
    bool pop();
    T top()const;
    T pop_top();
    T second()const;
protected:
private:
    int front;
    int rear;
    int len;
    T* elems;
};

#include "CycQueue.cpp"
#endif

循环队列主要注意不要忘记%len,不然就都是莫名错误啦!
文章来源:http://liyuxia-life.spaces.live.com/Blog/cns!DA1B364675ACF35!271.entry

posted on 2009-04-10 10:12 幸运草 阅读(2647) 评论(0)  编辑 收藏 引用 所属分类: Algorithms


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理