鱼C论坛

 找回密码
 立即注册
查看: 2058|回复: 2

[技术交流] 关于约瑟夫问题代码的分享

[复制链接]
发表于 2020-2-27 18:12:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 ByTime 于 2020-2-27 18:22 编辑

用VScode写的


[code]//用循环链表模拟约瑟夫问题

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

typedef struct people
{
    int number;
    struct people *next;
}people;

int globoal;
//循环链表的创立    创建number个节点  返回头部链表指针
people *creat_struct(int number)
{
    
    int creat_people;
    int struct_size;
        people *head,*p1,*p2;
        globoal = number;
    struct_size = sizeof(people);
    head = p1 = (people*)malloc(struct_size);
    //printf("请输入:");
    //scanf("%d",&head->number);
    head->number = 1;
    for(creat_people=1;creat_people<number;creat_people++)
    {
        p2 = (people*)malloc(struct_size);
        p1->next = p2;
        p1 = p2;
        //fflush(stdin);
        //printf("请输入:");
        //scanf("%d",&head->number);
        p1->number = creat_people+1;
        p1->next = head;
    }
    //printf("head=%p,p1=%p,p2=%p\n",head,p1,p2->next);
    return head;
} 



//约瑟夫环问题
//head为传入循环链表的头结点,
//number为约瑟夫问题中的数到多少要杀掉的人数;
void joseph_problem(people *head,int number)
{
    people *del;
    int first_move = number-2;
    int after_move = number-1;
    int read;
        int move = 1;
    for(;move<=first_move;move++)
    {
        head = head->next;
    }
    del = head->next;
    head->next = head->next->next;
    printf("->%d",del->number);
    free(del);
    globoal--;
    while (globoal > after_move)
    {
        head = head->next->next;
        del = head->next;
        head->next = head->next->next;
        printf("->%d",del->number);
        free(del);
        globoal--;
    }
    read = globoal;
    while(read!=0)
    {
        printf("\n剩下:%d号\n",head->number);
        head=head->next;
        read--;
    }
}

int main()
{
    int pwd;
    people *headl;
   //41为约瑟夫问题中代表的人的数量
    head = creat_struct(41);
   //3代表每次数到多少杀掉的人
    joseph_problem(head,3);

    return 0;
}
[/code]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-2-27 18:12:56 | 显示全部楼层
运行结果:
->3->6->9->12->15->18->21->24->27->30->33->36->39->1->5->10->14->19->23->28->32->37->41->7->13->20->26->34->40->8->17->29->38->11->25->2->22->4->35
剩下:31号
剩下:16号
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-7 10:10:04 | 显示全部楼层
虽然实现了,但是过于复杂。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-7 17:13

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表