您的位置:首页 > 理论基础 > 数据结构算法

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

2015-07-08 20:23 459 查看
/*

功能:41个人围成一圈,第一个到第三个一次报数,数到3,自杀,下一个报1......

      求出自杀顺序!

时间:2015-07-08

人员:西瓜太郎

*/

#include <stdlib.h>

#include <stdio.h>

#define ElementType int

struct Node;

typedef struct Node *ptrNode;

typedef ptrNode List;

typedef struct Node

{

    ElementType data;

    struct Node *next;

}Node;

void initJosePList(List *L);

void deleteCirList(List L);

void printfCirList(List L);

int main()

{

    List L= NULL;//一定要初始化!!!

    initJosePList(&L);

    printfCirList(L);

    printf("\n约瑟夫:\n");

    deleteCirList(L);    

    return 0;

}

void initJosePList(List *L)

{

    List temp,target;

    int i = 1;

    while(i < 42)

    {

        if((*L) == NULL)//定义L的时候一定要初始化!!

        {

            (*L) = malloc(sizeof(struct Node));

            if(!(*L))

                exit(EXIT_FAILURE);

            (*L)->data = 1;

            (*L)->next = (*L);

            i++;

        }

        else

        {

            for(temp = (*L); temp->next != (*L); temp = temp->next)

                ;

            target = malloc(sizeof(struct Node));

            target->data = i;

            i++;

            temp->next = target;

            target->next = (*L);

        }    

    }

}

void deleteCirList(List L)

{

    List temp,target;

    int j;

    temp = L;

    for(j = 1; j < 42; j++)

    {

        temp = temp->next;

        target = temp->next;

        temp->next = target->next;

        temp = temp->next;

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

        free(target);        

    }

    printf("\n");

}

void printfCirList(List L)

{

    List temp;

    for(temp = L; temp->next != L; temp=temp->next)

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

    printf("  %d\n",temp->data);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息