Josephus环类问题,java实现

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

写出一个双向的循环链表,弄一个计数器,我定义的是到三的时候,自动删除当前节点,很简单。

packageCom;importjava.util.Scanner;/** 约瑟夫环问题,有n个人组成的圈,数到3的那个人出列,下个人继续从一开始*/publicclassJosephus {publicstaticvoidmain(String[] args) {

Scanner s=newScanner(System.in);intn =Integer.parseInt(s.nextLine());

Node first=newJosephus().startRun(n );intcount = 1;while(first.next !=first) {

first=first.next;

count++;if(count == 3) {

first.PRevious.next=first.next;

first.next.previous=first.previous;

first=first.next;

count= 1;

}

}

System.out.println("最后剩下来的数字为:"+first.n);

}publicNode startRun(intn) {

Node first=newNode();

first.previous=null;

first.n= n ;//这里给链表赋值,倒叙Node current =first;

Node last=first;while((--n)>0) {

current.next=newNode();

current=current.next;

current.n=n;

current.previous=last;

last=current;

}

current.next=first;

first.previous=current;returnfirst;

}classNode {intn ;

Node next;

Node previous;

}

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航