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;
}
}