一、定義節點
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;
}
@Override
public String toString() {
return "Boy{" +
"no=" + no +
", next=" + next +
'}';
}
}
二、創建一個first節點,當前沒有編號
private Boy first = new Boy(-1);
三、添加節點,構建成一個環形的鏈表
public void addBoy(int nums) {
if(nums < 1) {
System.out.println("num incorrect");
return;
}
//輔助指針,幫助構建環形鏈表
Boy curBoy = null;
//使用for構建環形鏈表
for (int i = 1; i <= nums; i++) {
//按照編號,構建小孩節點
Boy boy = new Boy(i);
//如果是第一個小孩
if(i == 1) {
first = boy;
//構成環
first.setNext(first);
//讓curBoy指向第一個小孩
curBoy = first;
}else {
curBoy.setNext(boy);
//形成環
boy.setNext(first);
//往後移動
curBoy = boy;
}
}
}
四、遍歷
public void showBoy() {
if(first == null) {
System.out.println("null");
return;
}
//因爲first不能動,所以仍然使用一個輔助指針完成遍歷
Boy curBoy = first;
while (true) {
System.out.println("num: " + curBoy.getNo());
if(curBoy.getNext() == first) {
break;
}
curBoy = curBoy.getNext();
}
}
五、根據用戶的輸入,計算節點出圈的順序
startNo:從第幾個節點開始數
countNum:數幾下
nums:最初有幾個節點在圈中
public void countBoy(int startNo, int countNum, int nums) {
if(first == null || startNo < 1 || startNo > nums) {
System.out.println("input incorrect");
return;
}
//創建輔助變量
Boy helper = first;
//讓helper指向最後一個節點
while (true) {
if(helper.getNext() == first) {
break;
}
helper = helper.getNext();
}
//報數前,先讓first和helper同時移動startNo-1次
for (int i = 0; i < startNo - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
//報數時,讓first和helper同時移動countNum-1次,然後出圈
while (true) {
//圈中只有一個節點
if(helper == first) {
break;
}
//讓first和helper同時移動countNum - 1
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
//這時first指向的節點,就是要出圈的小小孩節點
System.out.println("go out " + first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.println("最後留在圈中的編號:" + first.getNo());
}
六、測試
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1,2,5);
}