# 链表_约瑟夫环

c 同时被 2 个专栏收录
9 篇文章 0 订阅
16 篇文章 0 订阅

30个人围成一个圈 从第一个人开始报数 第七个人丢去喂鲨鱼；从下一个开始继续数第七人丢掉

pos = pos + m -1; 因为已经丢掉了一个人所以要大家的序号都减了1；而第一开始第一个人占据一个位置，所以位置变化为 pos = pos + m -1; 完整代码在最下面 ：

fun（）函数中
for (int i = 0; i < last_pos; i++)
{
if (list->next!=NULL)
{
list = list->next;
}
}

for (int i = 0; i <n; i++)

#include <iostream>
#include <cstring>

using namespace std;

typedef struct listpoint
{
int data;
listpoint *next;
listpoint *last;

}listpoint;

listpoint *creat_noraml_list(int n)
{
for(int i = 1;i<=n;i++){
normal = (listpoint*)malloc(sizeof(listpoint));
normal->data = i;
end->next = normal;
normal->last = end;
end = normal;                    //最后一个节点变成新节点
cout<<"检测输入数据地址："	<< normal<<endl;
}

}

listpoint* listn( listpoint* l1,int n)
{
listpoint*l2=l1;
for (int i = 1; i <= n; i++)
{
if (l2->next!=NULL)
{
l2 = l2->next;

}
}
return l2;

}

void delete_Point(listpoint*list,int n)
{
cout<<"头节点地址"<<list<<endl;
listpoint *p = list;
for (int i = 0; i < n; i++){
if(p->next!=NULL) p = p->next;
}
p->next->last = p->last;
p->last->next = p->next;
free(p);
}

void printInfo(listpoint* list,int n )
{
listpoint* p = list;
for(int i = 0; i< n;i++){
p = p->next;
cout<<p->data<<"   ";
}

}

int fun(listpoint*list,int m,int n)
{
int data;
listpoint *p;
int pos = 1;  //记录当前位置
int last_pos = n;

while(last_pos!=1){
pos = pos + m -1;
while (pos>last_pos) pos -= last_pos;
delete_Point(list,pos);
last_pos--;
printInfo(list,last_pos);
cout<<endl;	 }
for (int i = 0; i < last_pos; i++)
{
if (list->next!=NULL)
{
list = list->next;
}
}
cout<<"最终节点地址"<<list<<endl;
system("pause");
data = list->data;
return data;

}

int main()
{
int m = 7;
int n = 30;
listpoint* list;
list = creat_noraml_list(n);
int data = fun(list,m,n);
cout<<"最终赢家  "<< data;
system("pause");

return 0;
}

• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

01-07
09-11 9964

10-30 8440
03-27 1万+
11-26 5380
04-14 1275
10-19 89
04-04 1418
10-04 207
03-21 803
04-02 330
08-14 726
05-01 96
06-13 3428
12-25