数据结构实验之链表八:Farey序列

来源:互联网 发布:新能源就业前景 知乎 编辑:程序博客网 时间:2024/06/06 03:11

数据结构实验之链表八:Farey序列
Time Limit: 10MS Memory Limit: 600KB
Submit Statistic
Problem Description

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级序列所包含的每一个分数。
Input

输入一个整数n(0

#include<stdio.h>#include<stdlib.h>#include<string.h>struct node{    int a, b;    struct node* next;};struct node * creat(struct node * head, int n){    if(n!=1)//插入链表    {    struct node * p , *q;    p = head->next;    q = p->next;    while(q)    {        if(p->b+q->b<=n)        {        struct node * w;        w = (struct node *)malloc(sizeof(struct node));        w->a = p->a+q->a;        w->b = p->b+q->b;        p->next = w;        w->next = q;        p = q;        if(q->next)        q = q->next;        else            q = NULL;        }        else            {        p = p->next;        if(!q->next)        q = NULL;        else        q = q->next;            }    }    }    else//开始的时候先建立链表0/1 1/1    {        struct node *p, *q;        p = (struct node *)malloc(sizeof(struct node));        q = (struct node *)malloc(sizeof(struct node));        q->a = 1;        q->b = 1;        p->a = 0;        p->b = 1;        q->next = NULL;        head->next = p;        p->next = q;    }    return head;};void show(struct node * head){    struct node * p = head->next;    while(p)    {        for(int i=0;i<9;i++)        {            if(p->next)            {                printf("%d/%d\t", p->a, p->b);//注意制表符                p = p->next;            }            else if(!p->next)            {               printf("%d/%d\t", p->a, p->b);               p = NULL;               break;            }        }        if(p==NULL)            break;        printf("%d/%d\n", p->a, p->b);        if(p->next)            p = p->next;        else            p = NULL;    }}int main(){    int n;    scanf("%d", &n);    struct node * head;    head = (struct node *)malloc(sizeof(struct node));    head->next = NULL;    for(int i=1;i<=n;i++)    {        head = creat(head, i);    }    show(head);    return 0;}
原创粉丝点击