环形链表(约瑟夫环)-建立及出圈操作
package A_1;
public class cirlinkeddemo {
public static void main(String[] args) {
cirlinked cir = new cirlinked();
cir.addcirlinked(5);
cir.listcirlinked();
cir.outcirlinked(5,3,3);
}
}
class cirlinked{
private Boy first = new Boy(0);
public void addcirlinked(int nums) {
Boy curBoy = first;
if(nums<=0) {
System.out.printf("不能创建 %d 个节点的链表\n", nums);
return;
}
for(int i = 0;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 listcirlinked() {
if(first.getNo()==0) {
System.out.println("没有小孩");
return;
}
Boy curBoy = first;
while(true) {
System.out.printf("小孩编号为%d \n",curBoy.getNo());
if(curBoy.getNext() == first) {
break;
}
curBoy = curBoy.getNext();
}
}
public void outcirlinked(int num,int startno,int length) {
if(num<=0 || startno>num || length<=0 || startno<1 || first==null) {
System.out.println("输入数据不合法,检查后输入");
}
Boy helper = first;
while(true) {
if(helper.getNext()==first) {
break;
}
helper = helper.getNext();
}
for(int i = 0;i<startno-1;i++) {
first = first.getNext();
helper = helper.getNext();
}
while(true) {
if(helper == first) {
break;
}
for(int j=0;j<startno-1;j++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩节点%d 出圈\n",first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后的小孩节点为%d\n",first.getNo());
}
}
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;
}
}