rendered paste body
import java.io.*;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Josephus2
{
public static void main(String[] args) throws FileNotFoundException
{
String names = JOptionPane.showInputDialog("Enter the number of names: ");
String n = JOptionPane.showInputDialog("Enter the N: ");
ListNode head = new ListNode(Integer.parseInt(names), null);
head.setNext(head);
for(int i = Integer.parseInt(names)-1; i >= 1 ; i--)
head = insert(head, new Integer(i));
print(head);
for(int k = 1; k < Integer.parseInt(names); k++)
{
head = remove(head, Integer.parseInt(n));
print(head);
}
//
int win = ((Integer)(head.getValue())).intValue();
Scanner infile = new Scanner(new File("J_names.txt"));
head = new ListNode(infile.next(),null);
ListNode t=head;
for(int x=2;x<=Integer.parseInt(names);x++)
{
t.setNext(new ListNode(infile.next(),null));
t=t.getNext();
}
t.setNext(head);
replaceAt(head,"Josephus",win);
while(head.getNext()!=head){
print(head);
head=remove(head,Integer.parseInt(n));
}
print(head);
}
public static ListNode insert(ListNode p, Object obj)
{
ListNode end = p;
while(end.getNext() != p)
end = end.getNext();
p = new ListNode(obj, p);
end.setNext(p);
return p;
}
public static void print(ListNode p)
{
ListNode currentNode = p;
if(p == null)
return;
while(currentNode.getNext() != p)
{
System.out.print(currentNode.getValue() + " ");
currentNode = currentNode.getNext();
}
System.out.println(currentNode.getValue());
}
public static ListNode remove(ListNode p, int n)
{
for(int i = 1; i < n-1; i++)
{
p = p.getNext();
}
p.setNext(p.getNext().getNext());
p = p.getNext();
return p;
}
public static void replaceAt(ListNode p, Object obj, int pos)
{
ListNode t=p;
for(int x=0;x<pos-1;x++)
t=t.getNext();
t.setValue(obj);
}
}