数据结构实验之链表八:Farey序列
Time Limit: 10 ms Memory Limit: 600 KiB
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>
int n;
struct node
{
int a, b;
struct node *next;
};
struct node* create(int n)
{
struct node *head, *p, *q, *t;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
t = head;
p = (struct node*)malloc(sizeof(struct node));
p->next = NULL;
p->a = 0;
p->b = 1;
t->next = p;
t = p;
p = (struct node*)malloc(sizeof(struct node));
p->next = NULL;
p->a = 1;
p->b = 1;
t->next = p;
t = p;
p = head->next;
t = p->next;
while(t)
{
if((p->b+t->b)<=n)
{
q = (struct node*)malloc(sizeof(struct node));
q->next = NULL;
q->a = p->a + t->a;
q->b = p->b + t->b;
q->next = t;
p->next = q;
t = q;
}
else
{
p = p->next;
t = t->next;
}
}
return head;
}
void show(struct node*head)
{
struct node *p;
p = head->next;
int x=0;
while(p)
{
x++;
printf("%d/%d", p->a, p->b);
if(x%10==0)
{
printf("\n");
}
else
{
printf("\t");
}
p = p->next;
}
return;
}
int main()
{
scanf("%d",&n);
struct node *head;
head = create(n);
show(head);
return 0;
}
/***************************************************
User name: jk160532姜兴友
Result: Accepted
Take time: 0ms
Take Memory: 248KB
Submit time: 2017-10-08 16:27:57
****************************************************/