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

来源:互联网 发布:js转化为字符串 编辑:程序博客网 时间:2024/06/07 16:13
/*
功能: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);

}
0 0
原创粉丝点击