代码存档:
#include <stdio.h>
struct LNode {
int inum; // 数据域
struct Lnode *next; // 指针域
};
struct LNode *head,*p;
void CreateList ( void );//initial
void showList(const struct LNode *Head,int inum);
void Josephus(struct LNode *Js, int n, int m);
int main()
{
head = NULL;
int n=8,m=3;
int i = 0;
for(; i < 8; i++)
{
struct LNode *pTemp;
pTemp = (struct LNode*)malloc(1*sizeof(struct LNode));
pTemp->inum = (i+1);
pTemp->next = head;
if(i==0)
head = p = pTemp;
else
{
p->next = pTemp;
p=p->next;
}
}
showList(head,n);
Josephus(head, n, m);
printf("最后剩余节点:");
showList(head,1);
return 0;
}
void showList(const struct LNode *Head,int inum)
{
int itor = 0;
struct LNode *p = Head;
while(p&&itor<inum)
{
printf("第%d个节点的内容是%d\n",itor,p->inum);
p=p->next;
itor++;
}
}
void Josephus(struct LNode *Js, int n, int m) {
struct LNode *p = Js,*pre = NULL;
int i, j;
for ( i = 0; i < n-1; i++ ) { //执行n-1次
for ( j = 1; j < m; j++) //数m-1个人
{ pre = p; p = p->next; }
printf( "出列的人是%d\n", p->inum);
pre->next = p->next; free(p); //删去
p = pre->next;
}
head = p;//最后剩余节点首地址
}