单向环形链表解决约瑟夫问题
2021/9/11 6:04:55
本文主要是介绍单向环形链表解决约瑟夫问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
约瑟夫问题(有时也称为约瑟夫斯置换,是一个计算机科学和数学中的问题。在计算机编程的算法中,类似问题又称为约瑟夫环。又称“丢手绢问题”.)
代码实现:
class OneWayAnnularChainTableMain { public static void main(String[] args) { OneWayAnnularChainTable oneWayAnnularChainTable = new OneWayAnnularChainTable(); oneWayAnnularChainTable.add(5); oneWayAnnularChainTable.show(); oneWayAnnularChainTable.outstanding(1,2,5); } } public class OneWayAnnularChainTable { private NumberNode first = null; public void add(Integer num) { if (num < 1) { System.out.println("数值不可小于1"); } NumberNode curNode = null; for (int i = 1; i <=num; i++) { NumberNode numberNode = new NumberNode(i); if (i == 1) { first = numberNode; first.next = first; curNode = first; } else { curNode.next = numberNode; numberNode.next = first; curNode = numberNode; } } } public void show() { if (first == null) { System.out.println("链表为空"); } NumberNode numberNode = first; while (true) { System.out.println(numberNode.toString()); if(numberNode.next==first){ break; } numberNode=numberNode.next; } } public void outstanding(Integer startNo, Integer count, Integer size) { if (first == null || startNo < 1 || count > size) { System.out.println("参数错误"); return; } NumberNode helper = first; while (true) { if (helper.next == first) { break; } helper = helper.next; } for (int i = 0; i < startNo - 1; i++) { first = first.next; helper = helper.next; } while (true) { if (helper == first) { break; } for (int i = 0; i < count - 1; i++) { first = first.next; helper = helper.next; } System.out.println(first.id); first = first.next; helper.next = first; } System.out.println(helper.id); } } class NumberNode { public Integer id; public NumberNode next; public NumberNode(Integer id) { this.id = id; } @Override public String toString() { return "NumberNode{" + "id=" + id + '}'; } }
这篇关于单向环形链表解决约瑟夫问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-07如何利用看板工具优化品牌内容创作与审批,确保按时发布?
- 2025-01-07百万架构师第十一课:源码分析:Spring 源码分析:Spring源码分析前篇|JavaGuide
- 2025-01-07质量检测标准严苛,这 6 款办公软件达标了吗?
- 2025-01-07提升品牌活动管理的效率:看板工具助力品牌活动日历的可视化管理
- 2025-01-07宠物商场的精准营销秘籍:揭秘看板软件的力量
- 2025-01-07“30了,资深骑手” | 程序员能有什么好出路?
- 2025-01-07宠物公园的营销秘籍:看板软件如何帮你精准触达目标客户?
- 2025-01-07从任务分解到资源优化:甘特图工具全解析
- 2025-01-07企业升级必备指南:从传统办公软件到SaaS工具的转型攻略
- 2025-01-07一文告诉你IT项目管理如何做到高效