1,先創建一個節點,讓frist指向改節點,並形成環形
2,後面當我們每創建一個新節點,就把該節點加入已有環形鏈表中即可
遍歷環形鏈表
1.讓輔助指針,指向first
2然後用while遍歷
好了,上代碼
package yanhaochen;
import java.util.Scanner;
public class hello{
public static void main(String[] args) {
//test
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
System.out.println("請輸入編號範圍");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
circleSingleLinkedList.addBoy(n);
circleSingleLinkedList.showBoy();
}
}
//創建一個環形的單項鍊表
class CircleSingleLinkedList {
//創建一個first節點,沒有編號
private Boy first = null;
//添加小孩,構建環形鏈表
public void addBoy(int nums){
//nums數據校驗
if (nums<1){
System.out.println("數據不正確");
return;
}
//用for去創建鏈表
Boy curboy = null;
//輔助指針
for (int i=1;i<=nums;i++){
//創建節點
Boy boy = new Boy(i);
//如果是第一個小孩
if (i==1){
first=boy;
first.setNext(first);
//構成環狀
curboy=first;
}else {
curboy.setNext(boy);
boy.setNext(first);
curboy = boy;
}
}
}
//遍歷
public void showBoy(){
//鏈表是否爲空
if(first==null){
System.out.println("鏈表爲空!!");
return;
}
Boy curboy = first;
while (true){
System.out.printf("小孩的編號%d\n",curboy.getNo());
if (curboy.getNext()==first){
System.out.println("遍歷完畢");
break;
}
curboy=curboy.getNext();
//currboy後移
}
}
}
//創建一個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;
}
}