对原来的约瑟夫环进行修改:剩下最后的一个数字,并返回此数字在原来数组中的下标。
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int data;
int index;
struct student *next;
}node;
int hwyuesefu(int *a,int n,int k,int m)
{
int i=0;
node *p,*t,*r,*curr;
p=(node *)malloc(sizeof(node));
p->data=a[i];
p->index=0;
p->next=p;
curr=p;
for(i=1;i<n;i++)
{
t=(node *)malloc(sizeof(node));
t->data=a[i];
t->index=i;
curr->next=t;
curr=t;
}
curr->next=p;
while(p->next!=p)
{
for(int j=0;j<=m-1;j++)
{
r=p;
p=p->next;
}
r->next=p->next;
printf("%d->",p->data);
free(p);
p=r->next;
}
printf("\n");
printf("the last data is:");
printf("%d\n",p->data);
return (p->index);
}
void main()
{
int index;
int a[8]={6,3,7,9,8,0,4,10};
index=hwyuesefu(a,8,0,2);
printf("the index of the last data is:");
printf("%d\n",index);
}
运行结果:
7->0->6->8->3->10->9->
the last data is:4
the index of the last data is:6
本文介绍了一个修改版的约瑟夫环问题实现方案,通过单向链表数据结构来模拟游戏过程,最终找到并返回最后一个幸存者的原始下标。
543

被折叠的 条评论
为什么被折叠?



