## CSDN博客

### 约瑟夫环问题的程序

#include <stdio.h>
#include <stdlib.h>

typedef struct lnode
{
int data;
int code;
struct lnode* next;
}lnode, * list;

///////////////////////////////////////////////////////////////////////////////
//辅助函数
lnode* CreateNode()
{
lnode* p = (lnode*) malloc (sizeof(lnode));
if (!p)
{
exit(0);
}
return p;
}

void DestoryNode(lnode* p)
{
free(p);
}

list ListInsertFront(list l)
{
lnode *p = CreateNode();
p->next = l;
return p;
}

lnode* ListRemoveNext(list prev)
{
lnode* p = prev->next;
prev->next = p->next;
return p;
}

///////////////////////////////////////////////////////////////////////////////
// 创建过程
list CreateRingQueue(int nCount)
{
list tail, l= CreateNode();
l->data = 1;
l->code = nCount;

tail = l;
//printf("创建第0个,编号为%d, 自己在%pn",l->code, l);
for(int i = 1; i < nCount; i++)
{
l = ListInsertFront(l);
l->code = nCount - i;
l->data = 0;
//printf("创建第%d个,编号为%d, 自己在%p, 下一个是%pn", i, l->code, l, l->next);
}
tail->next = l; //环形表

return l;
}

//输入过程
void InitRingQueue(list l, int nCount)
{
list begin = l;
int j = 0;

while( j != nCount)
{
printf("输入第%d个的参数", j + 1);
scanf("%d", &begin->data);

if(begin->data > 0)
{
begin = begin->next;
j++;
}
}

}

//删除过程
list RemoveFromQueue(list l, int nIdx)
{
list begin = l, end = l->next;
int idx = nIdx;

while(begin != end)
{
//printf("从第%d个开始查找第%d个n", begin->code, idx);
//查找第n-1个,
for(int i = 0; i < idx; i++)
{
//printf("从第%d个编号为%dn", i, begin->code);
begin = begin->next;
}
//删除第n个
lnode * p = ListRemoveNext(begin);

//取出下一次的n值
idx = p->data;

DestoryNode(p);
end = begin->next;
}
return begin;
}

int main()
{
int n = 0;
printf("输入链表长度");
scanf("%d", &n);

if( n <= 0)
{
return 0;
}

list l = CreateRingQueue(n);
InitRingQueue(l, n);
lnode * last = RemoveFromQueue(l, 3);

printf("last is %d, data is %d", last->code, last->data);
return 0;
}

0 0