weixin_39598023
weixin_39598023
2017-08-16 08:34

新手学习链表时碰到的问题,求大神指导

  • java
  • 链表

图片说明
在eclipse中创造链表的时候出现的提示,请问是什么原因引起呢,如何解决

package text;

class Child {
int no;
Child nextchile = null;
public Child (int no){
this.no = no;
}
}
//环形链表
class CycLink {
//先定义一个指向第一个小孩的引用。
Child firstchild = null;
Child temp = null;
int len = 0;//表示共用多少个小孩。
int k = 0;
int m = 0;
//设置m
public void setM (int m) {
this.m = m;
}
//设置链表大小
public void setlen(int len) {
this.len = len;
}
//设置从第几个人开始数数
public void setK(int k) {
this.k = k;
}
//开始play
public void play() {
Child temp = this.firstchild;
//1、先找到开始数数的人
for (int i = 1;i < k;i ++) {
temp = temp.nextchile;
}
while (this.len != 1) {
//2、数m下
for (int j = 0;j < m;j ++) {
temp = temp.nextchile;
}
//找到要出圈的前一个小孩
Child temp2 = temp;
while (temp2.nextchile != temp) {
temp2 = temp2.nextchile;
}
//3、将数到m的小孩,退出圈去
temp2.nextchile = temp.nextchile;
//让temp指向下一个数数的小孩
temp = temp.nextchile;
this.len --;
}
//最后一个小孩
System.out.print(temp.no);
}
//初始化环形链表
public void cheateLink () {
for (int i = 1;i <= len;i++) {
if(i == 1) {
//创建第一个小孩
Child ch = new Child(i);
this.firstchild = ch;
this.temp = ch;
}
else {
if (i == len) {
Child ch = new Child(i);
temp = ch;
temp.nextchile = this.firstchild;

            }
            else {
            //继续创建小孩
            Child ch = new Child (i);
            temp.nextchile = ch;
            temp = ch;
            }
        }
    }
}
public void show () {
    Child temp = this.firstchild;
    do {
        System.out.print(temp.no);
        temp = temp.nextchile;
    }while (temp != this.firstchild);
}

}

public class Josephu {
public static void main(String[] args) {
CycLink cyclink = new CycLink();
cyclink.setlen(5);
cyclink.createLink();
cyclink.setK(2);
cyclink.setM(2);
cyclink.show();
cyclink.play();
}

}
源码如下

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐