12.4循环链表、链表节点的删除--约瑟夫环

之所以将这段代码再敲一次,因为这段代码有几点值得学习。

1.对于链表,可以很方便的在表头插入数据,但是如果保留一个尾节点,则可以很方便的尾部插入节点。

2.不用专门定义一个指针来保留欲删除节点的父节点,只需要在数数的时候少数一个即可。如代码中:if( count == stride - 1)




代码示例:

#include <stdio.h> struct Monkey { int ID; Monkey *next; }; int main(int argc, char* argv[]) { Monkey *link, *monkey, *lastMonkey; int totalMonkeys, stride, count; printf("Please input the numbers of Monkeys:\n"); scanf("%d", &totalMonkeys); printf("Please input a number for striding:\n"); scanf("%d", &stride); link = NULL; for( int i = 0; i < totalMonkeys; i++) { monkey = new Monkey; monkey ->ID = i + 1; if( link == NULL) { link = lastMonkey = monkey; } else { lastMonkey->next = monkey; lastMonkey = monkey; } } lastMonkey->next = link; count = 1; printf("猴子出队的顺序:"); while( link != NULL) { if( link->next == link ) { printf("%4d\n", link->ID); delete link; break; } if( count == stride - 1) { monkey = link->next; link->next = monkey->next; printf("%4d", monkey->ID); delete monkey; monkey = NULL; count = 0; } link = link->next; count++; } return 0; }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值