写个约瑟夫环,检验一下自己的学习状况.............................
#include <stdio.h>
#define ElemType int
typedef struct LNode{
ElemType data;
int num;
struct LNode *next;
}SqList;
void InitList(SqList **L, ElemType n);
void Round(SqList *L, int m, int n);
int main()
{
SqList *L;
int n, m;
printf("the first number m:\n");
scanf("%d", &m);
printf("the number of students:\n");
scanf("%d", &n);
InitList(&L, n);
Round(L, m, n);
free(L);
return 0;
}
void InitList(SqList **L, ElemType n)//建立循环链表
{
SqList *s, *r;
int i;
ElemType a;
*L = (SqList *)malloc(sizeof(SqList));
r = *L;
scanf("%d", &a);
(*L)->num = 1;
(*L)->data = a;
for (i = 1; i < n; i++)//使用尾插法
{
s = (SqList*)malloc(sizeof(SqList));
scanf("%d", &a);
s->data = a;
s->num = i + 1;
r->next = s;
r = s;
}
r->next = *L;
}
void Round(SqList *L, int m, int n)
{
int still = n;//still 里面存的是还有多少人
int count = 1;
while (still != 0)
{
if (m == 1)//处理密码是1的情况
{
printf("%d\n",L->num);
m = L->data;
L->data = L->next->data;
L->num = L->next->num;
L->next = L->next->next;
count = 1;
still--;
continue;
}
else if (count == m - 1)//报到了的话
{
printf("%d\n", L->next->num);//打印出列的数
m = L->next->data;//报的数要进行变化
L->next = L->next->next;//删除节点(注意这里应该是放在最后面来进行的)
still--;//总共参与的人数要相应的减少1
count = 1;//重新开始计数
L = L->next;
continue;
}
else
{
count++;
L = L->next;
}
}
}