【转】约瑟夫环算法---------题目:有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位.

提示:用环形链表实现

对于这个题目其实就是用c语言的循环链表实现一个约瑟夫环。我们可以定义一个循环链表,将这n个人加入到链表中,然后定义三个节点指针在链表上循环,移动跨度为3,利用链表的循环功能每次删除第三个节点,这边要注意的一个问题就是你定义的是3个指针,且在循环中他们彼此也都是有

->next关系,一般我们判断循环结束条件时都是一个节点的下一个节点是否为它本身(如ptr->next == ptr),这里我们要注意循环体中链接方向否则很可能出现无用指针导致错误,因为最后我们要剩下一个节点那么ptr->next为NULL,而剩下的不能是NULL->next.

具体程序,如下:

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int num;
    struct node *next;
};

struct node *head;
struct node *last;

void cre_list()
{
    head = (struct node *)malloc(sizeof(struct node));
    last = head;
    head->next = head;
}

 

void display_node()
{
    struct node *ptr = head->next;
    while(ptr != head)
    {
        printf("%d ",ptr->num);
        ptr = ptr->next;
    }
    printf(" ");
}

void add_node(int num)
{
    struct node *ptr = (struct node *)malloc(sizeof(struct node));
    ptr->num = num;
    ptr->next = head;
    last->next = ptr;
    last = ptr;
}

void rev_node()
{
    struct node *ptr = head;
    last->next = head->next;
    head = head->next;
    free(ptr);
}

void tiren_node()
{
    struct node *ptr = head;
    struct node *str = ptr->next;
    struct node *qtr = str->next;
    while(ptr->next != ptr)
    {
        str = ptr->next;
        qtr = str->next;
        str->next = qtr->next;
        ptr = str->next;
    }
    printf("%d ",ptr->num);
}

int main()
{
    int i = 0;
    cre_list();
    int n;
    printf("please input n: ");
    scanf("%d",&n);
    printf("%d ",n);
    for(i = 1;i <= n;i++)
    {
        add_node(i);
    }
    display_node();
    rev_node();
    tiren_node();
    return 0;
}

原文地址:https://www.cnblogs.com/yihujiu/p/6627822.html