单链表2(Farey序列)

Farey序列是一个这样的序列:其第一级序列定义为(0/1,1/1),这一序列扩展到第二级形成序列(0/1,1/2,1/1),扩展到第三极形成序列(0/1,1/3,1/2,2/3,1/1),扩展到第四级则形成序列(0/1,1/4,1/3,1/2,2/3,3/4,1/1)。以后在每一级n,如果上一级的任何两个相邻分数a/c与b/d满足(c+d)<=n,就将一个新的分数(a+b)/(c+d)插入在两个分数之间。对于给定的n值,依次输出其第n级序列所包含的每一个分数。

输入

输入一个整数n(0<n<=100)

输出

依次输出第n级序列所包含的每一个分数,每行输出10个分数,同一行的两个相邻分数间隔一个制表符的距离。

样例输入

6

样例输出

0/1   1/6   1/5   1/4   1/3   2/5   1/2   3/5   2/3   3/4

4/5   5/6   1/1

#include"iostream"
using namespace std;
class List{
private:
    int mole;
    int deno;
    List *next;
public:
    List(int mole = 0,int deno = 0){
        this->mole = mole;
        this->deno = deno;
        this->next = NULL;
    }
    void deleteNote(){            //删除后一个结点
        List *temp = this->next;
        this->next = this->next->next;
        delete temp;
    }
    void show(){
        List *p = this->next;
        while(p){
            cout<<p->mole<<"/"<<p->deno<<"  ";
            p = p->next;
        }
        cout<<endl;
    }
    List *insertf(int mole,int deno){
        List *newp = new List(mole,deno);
        if(!newp){
            cout<<"out of space!"<<endl;
            return NULL;
        }
        newp->next = this->next;
        this->next = newp;
        return newp;
    }
    void fraction(int n){
        List *p = this;
        int i = 1;
        p = p->insertf(0,1);
        p->insertf(1,1);
        while(i++!=n){
            p = this->next;
            while(p->next){
                if(p->deno + p->next->deno <= i){
                    p = p->insertf(p->mole + p->next->mole,p->deno + p->next->deno);
                }
                p = p->next;
            }
        }
    }
};
    
int main(){
    List L,*p = &L;
    L.fraction(1000);
    L.show();
    return 0;
}

 

posted @ 2018-05-13 19:42  oleolema  阅读(216)  评论(0编辑  收藏  举报