约瑟夫问题

来源:互联网 发布:西南交大利兹学院知乎 编辑:程序博客网 时间:2024/04/27 20:43

链表

#include <stdio.h>#include <malloc.h>#define LEN sizeof(struct node)typedef struct node{    int num;    struct node *next;}node;node *creat(int n){    int i;    node *head,*tail,*p;    head = (node*)malloc(sizeof(LEN));    head->num = 1;    head->next = NULL;    tail = head;    for(i=2;i<=n;i++){        p = (node*)malloc(sizeof(LEN));        p->num = i;        p->next = NULL;        tail->next = p;        tail = p;    }    tail->next = head;    return head;}int kill(node *head,int m){    int s = 0;;    node *p,*q;    p = head;    while(p->next!=head)//游动指针指向头结点(因为是从第一个开始数的        p = p->next;    while(p->next!=p){//判断圈中是否只剩下一个节点        q = p->next;//q为p的后继 要删除一个结点首先得知道它的前驱        s++;        if(s%m==0){            p->next = q->next;            free(q);        }        else            p = q;    }    return p->num;}int main(){    int n,m;    node *head;    scanf("%d %d",&n,&m);    head = creat(n);    printf("%d",kill(head,m));    return 0;}
0 0
原创粉丝点击