约瑟夫问题(双向循环链表)

思路:
循环链表模拟

#include

typedef struct node

{

    int code;

    struct node *pri;

    struct node *next;

}DOUBLE_LINKE_NODE_JOSEPH_CIRCLE;

int main()

{

    DOUBLE_LINKE_NODE_JOSEPH_CIRCLE *head = NULL;

    DOUBLE_LINKE_NODE_JOSEPH_CIRCLE *tail = NULL;

    DOUBLE_LINKE_NODE_JOSEPH_CIRCLE *temp = NULL;

    int sum = 0;

    printf("INPUT THE SUM :");

    scanf("%d",&sum);

    int i = 0;

    for(i = 1;i <= sum;i++)

    {

        temp = (DOUBLE_LINKE_NODE_JOSEPH_CIRCLE *)malloc(sizeof(DOUBLE_LINKE_NODE_JOSEPH_CIRCLE));

        printf("INPUT THE CODE:");

        scanf("%d",&temp->code);

        temp->pri = NULL;

        temp->next = NULL;

        if(head == NULL)

        {

            head = temp;

            tail = temp;

        }

        else

        {

            tail->next = temp;

            tail->next->pri = tail;

            tail = temp;

        }

    }

    head->pri = tail;

    tail->next = head;

    int kill_num = 0;

    int kill_loop = 0;

    int kill_step = 0;

    printf("INPUT THE KILL LOOP:");

    scanf("%d",&kill_loop);

    while(1)

    {

        temp = head;

        head = head->next;

        kill_step++;

        if(kill_step % kill_loop == 0)

        {

            temp->pri->next = temp->next;

            temp->next->pri = temp->pri;

            free(temp);

            temp = head->pri;

            kill_num++;

        }

        if(kill_num + 1 == sum)

        {

            printf("SURVIVE CODE:%d",head->code);

            break;

        }

    }

    return 0;

}

你可能感兴趣的:(随笔)