某同学的数据结构作业 - 约瑟夫环变种

Who is the last?(链表实现)

题目描述

There are N people, numbered from 1 to N, sitting around in a circle. Counted from the NO.1, the M.th people should leave the game. Then, from the next one, the counting loop will go on. After several loops, there will be only one guy left. Writing a program to calculate who is the last people.

输入格式

Two integers, separated by commas. The first integer represents n individuals (0<N), the second integer represents M (0<M<=N).

输出格式

N integers, separated by commas. These number indicate the order of the person to leave the circle, with their numbers.

输入样例

5,1

输出样例

2,4,1,5,3

Tips

  • 与约瑟夫环相比,本题计数k由0开始
  • 并将经典约瑟夫环结构去掉密码
  • 取消根据每人手持密码对M的重新赋值操作即可。

Answer

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

typedef struct node
{
    int no;
    struct node *next;
}Node,*LinkList;

LinkList create_list(int n) ;
void Joseph(LinkList tail, int n, int m) ;
int main(void)
{
    LinkList tailptr;
    int n, m;
    scanf("%d %d",&n,&m);
    tailptr = create_list(n);
    /*创建含有n个结点的单循环链表*/
    if (tailptr)
    {
        Joseph(tailptr, n, m);
    }
    return 0;
}
/*用尾插法创建一个结点数为n的单循环链表,返回值为尾结点的指针*/
LinkList create_list(int n)
{
    LinkList p, rear;
    int i;
    /*先创建循环链表的第一个结点*/
    p = (Node *)malloc(sizeof(Node));
    if (!p) {
        printf("memory allocation error!\n");   return NULL;
    }
    p->no = 1;
    p->next = p;
    rear = p;
    /*创建循环链表的其余n-1个结点*/
    for(i = 2; i <= n; i++)
    {
        p = (Node *)malloc(sizeof(Node));
        if (!p)
        {
            printf("memory allocation error!\n");
            return NULL;
        }
        p->no = i;
        p->next = rear->next;
        rear -> next = p;
        rear = p;
    }
    return rear;
}/* create_list */

void Joseph(LinkList tail, int n, int m)
{
    LinkList pre, p;
    int k;
    m = m % n ? m % n : n;
    pre = tail;
    p = tail -> next;
    k = 0;
    while (n > 1)
    {
        /*圈中多于1个人时循环*/
        if (k == m)
        {
            /*数到需要出去的人(结点)时进行出圈处理*/
            printf("%d", p->no);
            /*p指向的结点为需要删除的结点*/
            pre -> next = p -> next;
            n--;
            free(p);
            p = pre -> next;
            k = 0;
        }
        else
        {
            k++;
            pre = p;
            p = p->next;
        }
    }/*while*/
    printf("%d\n", p->no);
}/*Joseph*/

转载于:https://www.cnblogs.com/vanlion/p/classmates-joseph.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值