定义节点类
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;
}
}
定义环形的单链表类
class CircleSingleLinkedList {
private Boy first = new Boy ( - 1 ) ;
public void add ( int nums) {
if ( nums < 1 ) {
System . out. println ( "nums的值不正确" ) ;
return ;
}
Boy cur = null ;
for ( int i = 0 ; i < nums; i++ ) {
Boy boy = new Boy ( i+ 1 ) ;
if ( i == 0 ) {
first = boy;
first. setNext ( first) ;
cur = first;
}
else {
boy. setNext ( first) ;
cur. setNext ( boy) ;
cur = cur. getNext ( ) ;
}
}
}
public void show ( ) {
if ( first == null ) {
System . out. println ( "链表为空~~" ) ;
return ;
}
Boy cur = first;
while ( true ) {
System . out. printf ( "小孩的编号 %d \n" , cur. getNo ( ) ) ;
if ( cur. getNext ( ) == first) {
break ;
}
cur = cur. getNext ( ) ;
}
}
}
测试代码
package com. atguigu. linkedlist ;
public class Joseph {
public static void main ( String [ ] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList ( ) ;
circleSingleLinkedList. add ( 5 ) ;
circleSingleLinkedList. show ( ) ;
}
}
运行结果
D:\java\jdk-11.0.11\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.1.1\lib\idea_rt.jar=2215:D:\IntelliJ IDEA 2020.1.1\bin" -Dfile.encoding=UTF-8 -classpath E:\WHT\Project\Java\DataStructures\out\production\DataStructures com.atguigu.linkedlist.Joseph
小孩的编号 1
小孩的编号 2
小孩的编号 3
小孩的编号 4
小孩的编号 5
Process finished with exit code 0