package test1;
/**
- Q:为什么要在i==1时的temp前要加this才行?其他的一加就出现空指针异常
- 顺序的排列为什么是必要的?
- **/
public class Jushon问题 {
public static void main(String[] args) {
// TODO Auto-generated method stub
createLink cl = new createLink();
cl.setLen(5);
cl.create();
cl.show();
}
}
//创建属性类
class child{
int no;
child nextchild = null;
public child(int no){
this.no = no;
}
}
//创建环形链表
class createLink{
/*
* 特殊位:第一位、最后一位
* 且每一位都与下一位关联
* 关联关系由游标(temp)指定
* */
child firstchild = null;
child temp = null;
//设定长度
int len = 0;
public void setLen(int len){
this.len = len;
}
public void create(){
for(int i = 1 ;i <= len ;i++){
if(i == 1){
child ch = new child(i);
this.firstchild = ch;
this.temp = ch;
temp.nextchild = ch;
}
else if(i == len){
child ch = new child(i);
temp.nextchild = ch;
temp = ch;
temp.nextchild = firstchild;
}
else{
// if(i == len){
// child ch = new child(i);
// temp.nextchild = ch;
// temp = ch;
// temp.nextchild = firstchild;
// }else{
child ch = new child(i);
temp.nextchild = ch;
temp = ch;
// }
}
}
}
//打印环形链表
public void show(){
child temp = this.firstchild;
do{
System.out.println(temp.no);
temp=temp.nextchild;
}while(temp != this.firstchild);
}
}