package com.structure.demo; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class JosephActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_joseph); CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList(); /* circleSingleLinkedList.addBoy(3); circleSingleLinkedList.show();*/ circleSingleLinkedList.addBoy(5); circleSingleLinkedList.countBoy(1, 2, 5); } } class CircleSingleLinkedList { Boy first = null; Boy curBoy = null; public void addBoy(int nums) { if (nums < 1) { Log.i("tag", "nums不合法"); } for (int i = 1; i <= nums; i++) { Boy boy = new Boy(i); if (i == 1) { //当前小孩付给第一个小孩 first = boy; //第一个小孩的后一个指向第一个小孩形成链表 first.next = first; //把第一个小孩设置为当前元素 curBoy = first; } else { //把当前小孩设置为下一个元素 curBoy.next = boy; //把第一个小孩设置为当前小孩的下一个节点 boy.next = first; //设置当前节点 curBoy = boy; } } } public void show() { if (first == null) { Log.i("tag", "链表为空"); return; } Boy curBoy = first; while (true) { Log.i("tag", "当前小孩的编号为" + curBoy.no); if (curBoy.next == first) { break; } curBoy = curBoy.next; } } /** * 约瑟夫问题的小孩出圈 * @param startNo 开始的小孩的编号 * @param countNo 每隔几个小孩出圈 * @param nums 一共的小孩的个数 */ public void countBoy(int startNo, int countNo, int nums) { if (first == null || countNo < 1 || startNo > nums) { Log.i("tag", "参数输入有误,请重新输入"); return; } //创建辅助指针帮助小孩出圈 Boy helper = first; //创建一个辅助指针,指向链表的最后 while (true) { if (helper.next == first) { break; } helper = helper.next; } //小孩报数前,先让first和helper移动到开始报数的位置(startNo) for (int i = 0; i < startNo - 1; i++) { first = first.next; helper = helper.next; } //当小孩报数时先让first和helper同时移动countNum-1次,然后出圈 while (true) { if (helper == first) { break; } for (int i = 0; i < countNo - 1; i++) { first = first.next; helper = helper.next; } Log.i("tag", "出圈的小孩的编号是" + first.no); first = first.next; helper.next = first; } } } class Boy { int no; Boy next; public Boy(int no) { this.no = no; } }
算法和数据结构——约瑟夫问题
最新推荐文章于 2022-11-20 20:54:51 发布