直接附源码,源码分为三部分:Boy类(人),Circle类(圆圈),TestBoy类(测试类)。
public class Boy {
private int no;
private Boy next;
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
public Boy(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
public class Circle {
private Boy first=new Boy(-1);
public void addBoy(int nums){
if (nums<1){
System.out.println("数据无意义");
return;
}
Boy temp=null;
for(int i=1;i<=nums;i++){
Boy boy =new Boy(i);
if (i==1){
first=boy;
first.setNext(first);
temp=first;
}else{
temp.setNext(boy);
boy.setNext(first);
temp=boy;
}
}
}
public void showBoy(){
if (first==null){
System.out.println("链表为空");
return;
}
Boy boy=first;
while (true){
System.out.println("节点编号为:"+boy.getNo());
if (boy.getNext()==first){
break;
}
boy=boy.getNext();
}
}
public void countBoy(int start,int count,int nums){
if (first==null||start<1||start>nums){
System.out.println("参数输入有误");
return;
}
Boy temp=first;
while (true){
if (temp.getNext()==first){
break;
}
temp=temp.getNext();
}
for (int j=0;j<start-1;j++){
first=first.getNext();
temp=temp.getNext();
}
while (true){
if (temp==first){
break;
}
for (int i=0;i<count-1;i++){
first=first.getNext();
temp=temp.getNext();
}
System.out.printf("编号为%d的人出列\n",first.getNo());
first=first.getNext();
temp.setNext(first);
}
System.out.println("最后出圈的人编号为:"+first.getNo());
}
}
public class TestBoy {
public static void main(String[] args) {
Circle circle=new Circle();
circle.addBoy(5);
circle.showBoy();
circle.countBoy(1,2,5);
}
}
运行结果:
在这里插入代码片节点编号为:1
节点编号为:2
节点编号为:3
节点编号为:4
节点编号为:5
编号为2的人出列
编号为4的人出列
编号为1的人出列
编号为5的人出列
最后出圈的人编号为:3