package com.heima.test;
import javax.sound.midi.Sequence;
/*
* 约瑟夫环
* 1-3,每逢3的倍数杀人,知道杀光为之
* 1: 创建链表,个数为传进去的num数
* 2:杀人方法,每逢3的倍数杀人(静态变量),如果next后检查%3==0,当前的指向上一个,下一个指向当前
* 3:杀人方法: 如果当前人数==1(如果当前人数没有下一个和上一个),不再杀人..返回编号
* */
public class Test8_Linked {
public static Child lastChild;
public static Child first;
public static void main(String[] args) {
addToSequence(100);
Child remainChild = delChild();
System.out.println("------------剩余-------");
System.out.println(remainChild);
}
static void showChild(){
Child c = first;
System.out.println(c);
for (c = first.next; c != first; c = c.next) {
System.out.println(c);
}
}
static Child delChild(){
Child c = first;
for ( int i = 1; c.next!=c; c = c.next,i++) {
if(i%3==0){
System.out.println("干掉了"+ c.getId());
c.delSelf();
}
}
return c;
}
private static void addToSequence(int num) {
for (int i = 1; i <= num; i++) {
Child c = new Child("a", i);//新加的孩子
if(i==1) {//第一个小朋友
first = c;
}else{
if(num ==i) {
//将首尾连接
first.previous = c; //第一个的前面一个设置为最后一个
c.next = first;//最后一个的后面设置为第一个
}
//一般情况
lastChild.next = c;//补写上次对象的后一个
c.previous = lastChild;//本次对象的前一个就是上次记录的
}
lastChild = c;//记录上次的孩子
}
}
}
class Child {
public Child next;
public Child previous;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Child getNext() {
return next;
}
public void setNext(Child next) {
this.next = next;
}
public Child getPrevious() {
return previous;
}
public void setPrevious(Child previous) {
this.previous = previous;
}
@Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
private String name;
public Child(String name, int id) {
super();
this.name = name;
this.id = id;
}
private int id;
public void delSelf(){
//我的后面的前面 是 我的前面 那我呢? 没有了
this.next.previous = this.previous;
//我前面的后面本该是我,现在是我后面的那个了,不是我没有了吗?
this.previous.next = this.next;
}
|
|