SDUT - 3535 3n+1数列问题

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

猜你喜欢

转载自blog.csdn.net/Miracle_QSH/article/details/81699592
今日推荐