马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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] |