我也是最近才开始重新学,不要问为什么,只是因为之前学的不咋地,如有误,请指出。
首先创建一个循环链表,使用first指向开始的数据,helper指向最后一个数据,通过循环的方式逐渐输出数据,并把输出后的数据从链表中移除。看代码
class Boy { private int no;//编号 private Boy next;//指向下一个节点 public Boy(int no) { this.no = no; } public int getNo() { return no; } public Boy getNext() { return next; } public void setNext(Boy next) { this.next = next; } }
/** * @param startNo 表示从第几个数据开始 * @param countNum 表示数几下 * @param nums 表示最初有几个数据 */ public void countBoy(int startNo, int countNum, int nums) { //先对数据进行校验 if (first == null || startNo < 1 || startNo > nums) { System.out.println("数据有误"); return; } //创建辅助指针 Boy helper = first; //使helper指向最后一个数据 while (helper.getNext() != first) { helper = helper.getNext(); } //先把first移动到startNo位置 //自己算第一个所以移动startNo-1次 for (int i = 0; i < startNo - 1; i++) { first = first.getNext(); helper = helper.getNext(); } //出数据 while (first != helper) { //数数出圈 for (int i = 0; i < countNum - 1; i++) { first = first.getNext(); helper = helper.getNext(); } System.out.println(first.getNo()); first = first.getNext(); helper.setNext(first);//删除输出后的数据 } System.out.println(first.getNo());//输出最后一个数据 }