📄 josephuslinkedlist.java
字号:
import javax.swing.JOptionPane;
public class JosephusLinkedList{
public static void main(String[] args){
String peopleString=JOptionPane.showInputDialog(null,"Enter the number of people:","Josephus Input",JOptionPane.QUESTION_MESSAGE);
//Enter the time to count
String timeString=JOptionPane.showInputDialog(null,"Enter the time to count:","Josephus Input",JOptionPane.QUESTION_MESSAGE);
//Convert String to int
int numberOfPeople=Integer.parseInt(peopleString);
int timeOfCount=Integer.parseInt(timeString);
Circle circle=new Circle(numberOfPeople);
while(circle.getLength()!=1){
circle.advanceAndRemove(timeOfCount-1);
}
System.out.println(circle.getCurrent().getValue()+" is the winner!");
}
}
class Node{
private int element;
private Node next;
public Node(){
this(1,null);
}
public Node(int value,Node n){
element=value;
next=n;
}
public void setValue(int value){
element=value;
}
public void setNextNode(Node n){
next=n;
}
public int getValue(){
return element;
}
public Node getNextNode(){
return next;
}
}
class Circle{
private int length;
private Node current;
private Node head;
private Node rear;
private Node p;
//p stands for the removed node
public Circle(){
this(5);
}
public Circle(int length){
this.length=length;
head=new Node(1,null);
rear=new Node(2,null);
current=head;
for(int i=0;i<length-1;i++){
head.setNextNode(rear);
head = rear;
rear = new Node(i+3, null);
}
head.setNextNode(current);
}
public Node getCurrent(){
return current;
}
public int getLength(){
return length;
}
public void advanceAndRemove(int m){
for(int i=0;i<m;i++)
current=current.getNextNode();
p=current.getNextNode();
System.out.println(p.getValue()+" is out!");
current.setNextNode(p.getNextNode());
length--;
current=current.getNextNode();
}
public boolean isPastEnd(){
return current==null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -