单向循环链表之约瑟夫环

环境:gcc

目的:单向循环链表练习

功能如下:

1. 创建一个单向循环链表

2. 在单向循环链表中每隔六个存储节点删掉一个存储节点

3. 一直循环2的规则,直至剩下最后一个节点



/*************************************************************************

 @Author: wanghao
 @Created Time : Wed 09 May 2018 06:08:28 PM PDT
 @File Name: ysfh.c
 @Description:
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>


#define N 33
#define M 7
#define K 1


typedef int data_t;


typedef struct node_t
{
data_t data;
struct node_t *pnext;
}Node;


Node *creat_empty_list(void)
{
Node *p;


p = (Node *)malloc(sizeof(Node));
if(p == NULL)
{
printf("fail!\n");
return NULL;
}


p->data = 0;
p->pnext = NULL;


return p;
}


int main(int argc, const char *argv[])
{
int i;
Node *start = NULL;
Node *next = NULL;


/*Create Joseph Ring list from 1 to 33*/
start = creat_empty_list();
if(!start)
{
printf("Create head node fail!\n");
return -1;
}
start->data = 1;
next = start;


for(i = 2; i <= N; i++)
{
next->pnext = creat_empty_list();
if(!next->pnext)
{
printf("Creat list node fail!\n");
return -2;
}
next->pnext->data = i;
next = next->pnext;
}

/*Form a loop list*/
next->pnext = start;


/*Determine the location of the homicide*/
next = start;
while(next->pnext != start)
{
if(next->data == K)
{
break;
}
next = next->pnext;
}


/*The game begain the position K*/
start = next;
while((start->pnext != start))
{
for(i = 1; i < M-1; i++)
{
start = start->pnext;
}

/*Find the killed position*/
next = start->pnext;
start->pnext = next->pnext;
start = next->pnext;
printf("%d was killed\n",next->data);
free(next);
next = NULL;
sleep(1);
}


printf("%d was alive\n",start->data);


return 0;


}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值