以前也处理过一个约瑟夫环问题。
但是以前处理那个比较简单。它的m是固定的
这次m删除一次结点后要变化。所以卡了很久
通过这个题,感觉自己调试程序的能力有所增强
fighting
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int id;
int password;
struct Node *next;
}Node;
Node *Create_Tail() {
printf("请输入初始人数: \n");
int m;
scanf("%d", &m);
Node *Head = NULL, *pNew = NULL, *r = NULL;
int passWord;
int ID = 1;
int count = 1;
printf("请输入第1个人的密码:\n");
scanf("%d", &passWord);
while (1) {
pNew = (Node *)malloc(sizeof(Node));
pNew->id = ID++;
pNew->password = passWord;
if (Head == NULL) {
Head = pNew;
r = pNew;
} else {
r->next = pNew;
r = pNew;
}
if (m == 1) {
break;
}
printf("请输入第%d个人的密码:\n", ++count);
scanf("%d", &passWord);
m--;
}
r->next = Head;
return r;
}
void Output(Node *r) {
Node *LA;
LA = r->next;
printf("编号:%d密码:%d\n", LA->id, LA->password);
LA = LA->next;
while (LA != r->next) {
printf("编号:%d密码:%d\n", LA->id, LA->password);
LA = LA->next;
}
}
int Count2(Node *r) {
Node *L = r->next;
int count = 1;
while (L != r) {
count++;
L = L->next;
}
return count;
}
void YueSeFu(Node *r, int m) {
int t = m;
Node *LA = r;
Node *LB = r->next;
while (1) {
if (Count2(LA) == 2) {
if (t % 2 == 1) {
printf("编号:%d 密码:%d\n\n", LB->id, LB->password);
printf("编号:%d 密码:%d\n", LA->id, LA->password);
break;
} else {
printf("编号:%d 密码:%d\n\n", LA->id, LA->password);
printf("编号:%d 密码:%d\n", LB->id, LB->password);
break;
}
} else {
for (int i = 1; i < t; i++) {
LA = LA->next;
LB = LB->next;
}
printf("编号:%d 密码:%d\n", LB->id, LB->password);
if (Count2(LA) == 1) {
break;
}
t = LB->password;
LB = LB->next;
printf("\n");
LA->next = LB;
}
}
}
int main() {
printf("开始建立循环链表: \n");
Node *LA;
LA = Create_Tail();
Output(LA);
int m;
printf("请输入初始密码: \n");
scanf("%d", &m);
printf("出队顺序: \n");
YueSeFu(LA, m);
return 0;
}