效果:
代码:
looplink.c
//约瑟夫环问题
int annular(LoopLink h,int n,int a)
{
//判断条件
if(NULL==h||list_empty(h))
{
printf("约瑟夫环创建失败\n");
return -1;
}
//约瑟夫环逻辑
LoopLink q=h;
for(int j=0;j<a;j++)
{
for(int i=0;i<n-2;i++)
{
q=q->next;
}
LoopLink p=q->next; //标记
q->next=p->next; //孤立
printf("%d\t",p->data);
free(p);
p=NULL;
if(p==NULL)
{
q=q->next;
}
}
printf("\n");
printf("约瑟夫环已经实现\n");
return 0;
}
main.c
#include"looplink.h"
#include <stdio.h>
int main(int argc, const char *argv[])
{
LoopLink L=list_create();
if(NULL==L)
{
return -1;
}
//调用头插函数
list_insert_head(L,7);
list_insert_head(L,8);
list_insert_head(L,5);
list_insert_head(L,8);
//调用遍历函数
list_show(L);
//调用任意位置插入函数
list_insert_pos(L,3,2);
list_show(L);
//调用尾插函数
list_insert_tail(L,1);
list_insert_tail(L,3);
list_show(L);
//调用头删函数
list_delete_head(L);
list_show(L);
//尾删
list_delete_tail(L);
list_show(L);
//定义一个变量接受链表结点个数
int a=L->len;
//去除头结点
LoopLink h=list_kill_head(L);
L=NULL;
//调用遍历函数
list_display(h);
//调用约瑟夫环函数
annular(h,4,a);
/* //释放
list_free(h);
h=NULL;
return 0;*/
}