约瑟夫环-链表

#include <stdlib.h> //非malloc
#include <stdio.h>

typedef struct LNode{
    int data;
    LNode* next;
    
}LNode,*Linklist;

void josephus(int n,int k,int m)
{
    Linklist cur,head,prior,temp;
    head=(Linklist)malloc(sizeof(LNode));
    head->data=1;
    head->next=head;
    
    cur=head;//当前节点设为头结点
    
    for (int i=2; i<=n; i++) {
        temp=(Linklist)malloc(sizeof(LNode));
        temp->data=i;
        temp->next=cur->next;
        cur->next=temp;
        cur=temp;
    }
    
    cur=head;//当前节点设为头结点
    
    while(--k)//注意此处是先--
    {
        prior=cur;
        cur=cur->next;
    }
    while (n--) {
        for (int i=0; i<m-1; i++) {
            prior=cur;
            cur=cur->next;
        }
        printf("%d
",cur->data);
        prior->next=cur->next;
        free(cur);
        cur=prior->next;
    }
    
    
}
原文地址:https://www.cnblogs.com/helo-blog/p/3354365.html