本系列博客源自学习《尚硅谷数据结构与算法》的学习随笔。
package test.learn.algorithm.Josepfu;
public 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;
}
}
package test.learn.algorithm.Josepfu;
public class CircleSingleLinkList {
Boy first = new Boy(-1);
//添加小朋友
public void addBoy(int nums){
if(nums<1){
System.out.println("nums值不正确!");
return ;
}
Boy temp = null;
for(int i = 1; i<=nums;i++){
if(i==1){
first = new Boy(i);
first.setNext(first);
temp = first;
}else {
temp.setNext(new Boy(i));
temp=temp.getNext();
temp.setNext(first);
}
}
}
//遍历
public void show(){
if(first==null){
System.out.println("没有小朋友");
return;
}
Boy temp = first;
while(temp.getNext()!=first){
System.out.print(temp.getNo()+" ");
temp = temp.getNext();
}
System.out.println(temp.getNo());
}
//小孩出圈
public void countBoy(int startNo,int countNum,int nums){
if(first==null||startNo<1||countNum>nums){
System.out.println("输入的参数有误,请重新输入");
return;
}
Boy helper = first;//辅助指针,指向first的前一个
while(helper.getNext()!=first){
helper = helper.getNext();
}
for(int j=0;j<startNo-1;j++){//将first跟helper移动到开始报数的地方
first = first.getNext();
helper = helper.getNext();
}
//开始报数出圈
while(helper!=first){//但圈中不只一位小朋友时
for(int j=1;j<countNum;j++){//报数
first = first.getNext();
helper = helper.getNext();
}
System.out.println(first.getNo());//让该小朋友出圈
first = first.getNext();
helper.setNext(first);
}
System.out.println(first.getNo());//让剩下的那位小朋友出圈
first = null;//置空
}
}
package test.learn.algorithm.Josepfu;
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkList c = new CircleSingleLinkList();
c.addBoy(5);
c.show();
System.out.println("--------------------------");
c.countBoy(1,2,5);
}
}