/*Joseph Problem
*利用单循环链表解决约瑟夫问题。
*问题描述:将n个数链接成一个环,从第m个开始,每次从1计数到s时
* 将s删除。从下一个开始再次从1计数至s时删除s。直到全
* 部删除为止。
* */
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
typedef struct Node* LinkList;
void CreateJosephLoop(LinkList *L,int number){
//创建Joseph环,在头结点中放入了元素1.
*L = (LinkList)malloc(sizeof(struct Node));
if(!(*L)){
printf("Error:malloc:0!\n");
exit(1);
}
(*L)->next = (*L);
(*L)->data = 1;
int i;
LinkList new;
LinkList tail = *L;
for(i = 1; i < number; i++){
new = (LinkList)malloc(sizeof(struct Node));
if(!new){
printf("Error:malloc:1+i");
exit(1);
}
new->data = i+1;
new->next = tail->next;
tail->next = new;
tail = new;
}
}
void JosephProblem(int loopSize,int from,int stepBy){
//loopSize:Joseph环的大小
//form:从from开始
//stepBy:每次计数到stepBy时删除stepBy所指向的元素
LinkList L;
CreateJosephLoop(&L,loopSize);
int seekStart = 1;
while(seekStart < from){
L = L->next;
seekStart += 1;
}
while(L->next != L){
int i = 1;
LinkList temp;
for(i = 1;i < stepBy - 1; ){
L = L->next;
i++;
}
temp = L->next;
printf("%d-->",temp->data);
L->next = L->next->next;
L = L->next;
free(temp);
}
printf("%d\n",L->data);
}
int main(){
JosephProblem(10,3,4);
JosephProblem(41,1,3);
return 0;
}
约瑟夫问题(单循环链表解决)
最新推荐文章于 2023-02-12 21:07:20 发布