[2016/7/29]JAVA之關於約瑟夫問題




/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//     作者:67                                                                                                                 //
//     時間:2016.7.29                                                                                                     //
//     目的:掌握鏈表,另一種方法代替Josephu問題中查找需要的刪除的節點部分                  //
/////////////////////////////////////////////////////////////////////////////////////////////////////////// 



import java.util.Scanner;
public class Jo {

public static void main(String[] args) {
// TODO Auto-generated method stub
  System.out.println("請輸入參加的活動的學生個數:");
  Scanner ss=new Scanner(System.in);
  int s=ss.nextInt();
  System.out.println("請輸入從第幾位學生開始數:");
  Scanner dd=new Scanner(System.in);
  int d=dd.nextInt();
  System.out.println("請輸入需要數的學生個數:");
  Scanner ff=new Scanner(System.in);
  int f=ff.nextInt();
      Lianbiao b=new Lianbiao(s);
      b.lianjie();
      b.begin(3);
      b.much(5);
}

}


//孩子類公共屬性
class Child
{
    int number;  //第幾個小孩
    Child nextchild=null;    //下一個小孩
    public Child(intnumber)
    {
   this.number=number;
    }
}

//形成鏈表
class Lianbiao
{
//首鏈表
Child firstchild=null;
//下一個鏈表
Child temp=null;
//幾位小孩子
int len=0;
Child temp2=null;
public Lianbiao(int len)
{
this.len=len;
}
//環形鏈表
public void lianjie()  
{
  for(int i=1;i<=len;i++)
 {    
Child a=new Child(i);//給孩子編號
if(i==1)    //爲第一個時
{
firstchild=a;
temp=a;
}
else if(1
{
temp.nextchild=a;
temp=a;
}
else if(i==len)//最後一個
{   
temp.nextchild=a;
temp=a;
temp.nextchild=firstchild;
}
System.out.print(" "+temp.number);//輸出鏈表
 }
  System.out.println(" ");
}
//第幾個開始數
public void begin(int m)
{
temp=firstchild;
for(int i=1;i
{
temp=temp.nextchild;
}
System.out.print("從第"+temp.number+"位小孩子開始數");
}
//數幾個
public void much(int n)
{ 
System.out.println(n+"位小朋友");
do{
    for(int i=1;i
    {
    if(i==n-2)  //前一位
    {
    temp=temp.nextchild;
    temp2=temp;
    }
    else{
    temp=temp.nextchild; //本身需要刪除的節點
       }
    }System.out.println("結果爲:編號爲"+temp.number+"的小朋友out。");
  //刪除
  temp2.nextchild=temp.nextchild; 
  temp=temp.nextchild;
len--;
}while(len!=1);
System.out.println("最後勝利者爲"+temp.number);
}
}

總結:學習時看到老師是用循環查找的方式找到需要刪除的節點的前一位,如果數據大會影響運行速度,所以我用直接用“替身”保留上一位的方式代替。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章