链表经典问题:约瑟夫环的实现

来源:互联网 发布:淘宝客服基础知识 编辑:程序博客网 时间:2024/05/20 01:10

对于约瑟夫环这个经典的链表问题,相信大家都不会陌生。

经常会以这种形式出现:

有13人围成一圈,从第一个人开始顺序报数,凡报到3的人退出圈子,编程找出最后留在圈子里的人原来的序号。


具体实现的代码如下:

#include <stdio.h>#include <stdlib.h>#define LEN 13#define NUM 3typedef struct node {    int num;    struct node *next;}node;int main(){    int i;    int length;    node *p;    node *ptr;    node *first;    first = (node *)malloc(sizeof(node));    if (first == NULL) {        printf("malloc fail!\n");        return -1;    }    first->num = 1;    p = first;    for(i = 1; i < LEN; i ++) {        p->next = (node *)malloc(sizeof(node));        p = p->next;        p->num = i+1;    }    p->next = first;    p = p->next;    length = LEN;    p = first;    while (length > 1) {        if (NUM == 1) {             for (i = 0; i < LEN - 1; i ++) {                 ptr = p;                p = p->next;                free(ptr);            }            printf("the last one left is %d\n", p->num);            free(p);            return 0;        } else {            for (i = 0; i < NUM - 2; i++) {                p = p->next;            }            ptr = p->next;            p->next = ptr->next;            p = p->next;            free(ptr);            length --;        }    }    printf("the last one is %d\n", p->num);    free(p);            return 0;}