這個專題記錄自己學習資料結構的過程,也希望能給自學的小夥伴一點幫助。
class Josephu{
private Boy first =null;
//增加
public void addBoy(int num){
if(num<1){
System.out.println("輸入資料錯誤");
}
Boy temp=null;
for(int i =1;i<=num;i++){
Boy boy=new Boy(i);
if(i==1){
first=boy;
temp=first;
boy.setNext(first);
}else {
temp.setNext(boy);
temp=temp.getNext();
boy.setNext(first);
}
}
}
//周遊
public void list(){
if(first==null){
System.out.println("環内無資料");
return;
}
Boy temp=first;
if(first.getNext()==first){
System.out.println(temp.toString());
return;
}
while (temp.getNext()!=first){
System.out.println(temp.toString());
temp=temp.getNext();
}
System.out.println(temp.toString());
}
//計數
public int sort(){
if(first==null){
return 0;
}
Boy temp=first;
if(first.getNext()==first){
System.out.println(temp.toString());
return 1;
}
int i =0;
while (temp.getNext()!=first){
i++;
temp=temp.getNext();
}
i++;
return i;
}
//環問題
public void countBoy(int start,int num){
int i=this.sort();
if(start<0||start>i){
System.out.println("輸入資料有錯誤");
return;
}
if(first.getNext()==first){
System.out.println(first.toString());
}
Boy helper=first;
while (helper.getNext()!=first){
helper=helper.getNext();
}
for(int j=1;j<start;j++){
first=first.getNext();
}
while(true){
if(first==helper){
break;
}
for(int j=0;j<num-1;j++){
first=first.getNext();
helper=helper.getNext();
}
System.out.println(first.toString());
helper.setNext(first.getNext());
first=first.getNext();
}
System.out.println(first);
}
}
class Boy {
private int id ;
private Boy next;
@Override
public String toString() {
return "Boy{" +
"id=" + id +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Boy getNext() {
return next;
}