链表:3n+1数列问题!!!

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

输出链表序列
Sample Input

10 5

Sample Output

2 4 8 5 16

#include<stdio.h>
#include<stdlib.h>
struct node {
struct node *next;
int data;
};
int main()
{

    int n, i, k;
    while(scanf("%d %d",&n,&k)!=EOF)
    {

    node *head = new node;              //因为多组输入,所以得在while里面建立头。
    head ->next = NULL;
    node *tail = head;
    if(n%2 != 0) n = n*3 + 1;           //××××××××××××××××××××
    else n = n/2;
    node *p = new node;
        p->data = n;                 这个范围的东西很重要,得先给空头插入一个数,
        p->next = NULL;          否则下面的头插接不上。因为在下面的插入中,如果刚开始
        tail->next = p;          就是头插,tail的指向没改变,还是跟着head!!!!!
        tail = p;                              //××××××××××××××××××××
    for(i = 2; i <= k; i++)           //这个for就容易理解了,偶数的话变成n/2,插到头
    {                                奇数变成3×n+1  放到尾部。

        if(n%2 != 0) {
        n = n*3 + 1;
        node *q = new node;
        q->data = n;
        q->next = NULL;
        tail->next = q;
        tail = q;
        }
        else
        {
        n = n/2;
        node *q = new node;
        q->data = n;
        q->next = head->next;
        head->next = q;                                   
        }
    }
    for(node *p = head->next; p != NULL; p = p->next)
    {
    if(p->next!=NULL) printf("%d ",p->data);
    else printf("%d\n",p->data);
    }

    }
    return 0;
}

                             加油鸭!!!!!

猜你喜欢

转载自blog.csdn.net/weixin_43822064/article/details/84944519