数据结构与算法之约瑟夫问题

#include<stdio.h>
#include<malloc.h>

/*约瑟夫问题--底层实现:动态队列*/

//定义队列结点类型
typedef struct People{

    int data;
    struct People *next;

}People;
//定义队列类型
typedef struct Node{

    People *head;
    People *tail;

}Queue;

int main(){

    People *New,*temp;
    Queue queue;
    int n,p;
    int i=1;

    New = (People*)malloc(sizeof(People));
    New->next = NULL;
    queue.head = New;
    queue.tail = queue.head;

    //n表示人数,p表示每次第p个人出局
    scanf("%d%d",&n,&p);

    //初始化队列
    while(i<=n){

        New = (People*)malloc(sizeof(People));
        New->data = i;
        New->next = NULL;

        queue.tail->next = New;
        queue.tail = New;
        i++;
    }

    New = queue.head->next;
    while(New!=NULL){
       i = 1;
       while(i<p){

            queue.tail->next = New;
            queue.tail = New;
            New = New->next;
            queue.tail->next=NULL;
            i++;
       }

       printf("%d ",New->data);

       temp = New->next;
       free(New);
       New = temp;

    }
    return 0;
}
    原文作者:LiChangBao
    原文地址: https://www.jianshu.com/p/f30da82c0c6f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞