一、约瑟夫问题
1、动态链表
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
int main(){
int n,m;
scanf("%d%d",&n,&m);
node *head,*p,*now,*prev;
//分配第一个节点,数据值为1
head = new node;
head ->data=1;
head->next=NULL;
now = head;
for (int i = 2;i<=n;i++){
p=new node;
p->data=i;
p->next=NULL;
now->next=p;
now = p;
}
now->next=head;
now = head,prev =head;
while((n--)>1){
for (int i = 1;i<m;i++){
prev = now;
now = now->next;
}
printf("%d%c",now->data,' ');
prev->next=now->next;
delete now;
now = prev->next;
}
printf("%d",now->data);
delete now;
return 0;
}
2、结构体实现静态链表
#include <bits/stdc++.h>
using namespace std;
struct node{
int prev,data,next;
}hh[100000];
int main(){
int n,m;
scanf("%d%d",&n,&m);
for(int i = 1;i<=n;i++){
hh[i].data=i;
hh[i].next=i+1;
hh[i].prev=i-1;
}
hh[1].prev=n;
hh[n].next=1;
int now = 1;
while((n--)>1){
for (int i = 1;i<m;i++){
now = hh[now].next;
}
printf("%d ",hh[now].data);
int pre = hh[now].prev,ne = hh[now].next;
hh[pre].next=hh[now].next;
hh[ne].prev=hh[now].prev;
now = ne;
}
printf("%d",hh[now].data);
return 0;
}