3n+1数列问题

Time Limit: 1000MS  Memory Limit: 65536KB
Problem Description

有一天小标遇到了经典的3n+1数链问题,他想知道3n+1数链的前k个数是多少。
下面小标来给你介绍一下3n+1数链是什么,
给定一个数n,如果n为偶数,那么下一个数n1 =  n / 2;否则n1 = 3 * n + 1;
                          如果n1为偶数,那么下一个数n2 =  n1 / 2;否则n2 = 3 * n1 + 1;
                          如果n2为偶数,那么下一个数n3 =  n2 / 2;否则n3 = 3 * n2 + 1;
                          .....
小标最近刚刚学习了链表,他想把这两个知识结合一下,所以,他想按照下面的规定去做。
①起始n为10,k为5,链表为空
②判断n为偶数,他会往链表头部加一个5(即n/2),此时链表中序列为5,n变为5 -> NULL
③接下来n==5,判断n为奇数,他会往链表尾部加一个16(即3*n+1),此时链表中序列为5 -> 16 -> NULL
④接下来n==16,判断n为偶数,他会往链表头部加一个8(即n/2),此时链表中序列为8 -> 5 -> 16 -> NULL
⑤接下来n==8,判断n为偶数,他会往链表头部加一个4(即n/2),此时链表中序列为4 - > 8 - > 5 -> 16 -> NULL
⑥接下来n==4,判断n为偶数,他会往链表头部加一个2(即n/2),此时链表中序列为2 - > 4 - > 8 - > 5 -> 16 -> NULL
到此时,小标得到了前k个数,那么输出这个序列。
Ps: 为了变得更容易理解,简单来说就是n为偶数,加在链表头部,n为奇数,加在链表尾部

Input

 多组输入。
对于每组数据,每行两个整数1 <= n , k <= 1000,含义如上

Output

 输出链表序列

Example Input
10 5
Example Output

2 4 8 5 16

//下面是代码  注意往链表的结尾插入一个新的结点的时候需要遍历整个链表, 才能到链表的结结尾,并不像是数组一样可以直接访问其中的任何一项//

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    int data;
    struct node *next;
};
struct node *head;
void creat(int n,int m);
void diaplay();
int main()
{
    int n,m;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        creat(m,n);
        diaplay();
    }
    return 0;
}
void creat(int n,int m)
{
    struct node *p,*q,*t;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    q=head;
    q->next=NULL;
    while(n--)
    {
        p=(struct node *)malloc(sizeof(struct node));
        if(m%2==0)
        {
             m=m/2;
             p->data=m;
             t=head;
             q=t->next;
             t->next=p;
             p->next=q;
        }
        else
        {
            m=3*m+1;
            p->data=m;
            for(t=head;t->next!=NULL;t=t->next);
            t->next=p;
            p->next=NULL;
        }


    }
}
void diaplay()
{
    struct node *q;
    q=head->next;
    while(q!=NULL)
    {
        if(q->next!=NULL)printf("%d ",q->data);
        else printf("%d\n",q->data);
        q=q->next;
    }
}




/***************************************************
Result: Accepted
Take time: 160ms
Take Memory: 8212KB
****************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值