3,环形链表
单向环形链表
单向环形链表介绍
案例:与瑟夫问题(josephu)
设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
代码实现:
/** * 构建一个单向环形链表的思路 * 1,先创建第一个节点,让first指向该节点,并形成环状 * 2,后面每创建一个节点,就把该节点加入到已经创建好的环形链表中 * * 环形链表的遍历 * 1,先让一个辅助指针curBoy 指向first节点 * 2,然后通过while循环遍历该环形链表即可,当curBoy.next == first 表示结束 */ public class Josephu { public static void main(String[] args) { CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList(); //测试生产一个单向环形链表 circleSingleLinkedList.addBoy(5); //遍历单向环形链表 circleSingleLinkedList.showBoyList(); //小孩出圈问题,从第1个开始数,数到2的小还出圈,圈中的小孩总数为5个 circleSingleLinkedList.countBoyOut(1,2,5); } } /** * 创建一个Boy类,表示单向环形链表一个节点 */ class Boy { private int no;//小孩编号 private Boy next;//默认为空,表示指向下一个小孩 public Boy(int no) { this.no = no; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public Boy getNext() { return next; } public void setNext(Boy next) { this.next = next; } } /** * 创建一个单向的环形链表对象 * 1,添加单向的环形链表对象个数 * 2,遍历显示单向的环形链表对象 */ class CircleSingleLinkedList { //创建first节点 private Boy first = new Boy(-1); /** * 添加小孩子节点,构建一个单向环形链表 * 思路: * 1,先创建第一个节点,让first指向该节点,并形成环状 * 2,后面每创建一个节点,就把该节点加入到已经创建好的环形链表中 * @param number :单向环形链表的长度 */ public void addBoy(int number){ if(number < 1) { System.out.println("number的值不正确!!"); return; } Boy curBoy = null;//辅助指针,帮助构建链表 //使用for循环来创建我们的环形链表 for(int i = 1; i <= number; i++) { Boy boy =new Boy(i); if(i == 1){ first = boy; first.setNext(first); curBoy = first;//让curBoy指向第一个小孩,即first }else { curBoy.setNext(boy);//将curBoy辅助指针(即first节点)和新加的节点连接起来 boy.setNext(first);//在将新加的节点的next连接到first节点形成环形链表 curBoy = boy;//然后将辅助指针指向新加的节点 } } } /** * 借助赋值指针curBoy遍历单向环形链表 */ public void showBoyList() { if(first == null) { System.out.println("链表为空!!"); return; } //因为first不能懂,因此我们使用一个辅助指针 Boy curBoy = first; while (true) { System.out.println("小孩的编号为:"+curBoy.getNo()); if(curBoy.getNext() == first){ break; } curBoy = curBoy.getNext();//当前辅助指针指向下一个节点 } } /** * 根据用户的输入计算出小孩出圈的顺序 * @param startNo 表示从第几个开始数 * @param countNum 表示数几个数 * @param numbers 原始圈中小孩的数量 */ public void countBoyOut(int startNo, int countNum, int numbers) { //对数据进行校验 if (first == null || startNo < 1 || startNo > numbers) { System.out.println("参数有误,请重新输入!!"); return; } //创建一个赋值指针,帮助小孩出圈 Boy helper = first; //需求创建一个赋值指针helper,事先指向单向环形链表的最后一个节点 while (true) { if (helper.getNext() == first) { break; } helper = helper.getNext(); } //报数前,先让first和helper移动k-1次 for (int i = 0; i < startNo - 1; i++) { first = first.getNext(); helper = helper.getNext(); } //当小孩开始报数时,让first和helper指针同时移动m-1次,然后出圈 while (true) { if (helper == first) { break; } //让first和helper指针同时移动countNum-1次 for (int j = 0; j < countNum - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //这时first指向的节点就是小孩出圈的节点 System.out.printf("小孩%d出圈\n", first.getNo()); //让出圈的小孩出圈 first = first.getNext(); helper.setNext(first); } System.out.println("最后留在圈中的小孩的编号为:" + first.getNo()); } }