-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJosephusProblem1.java
More file actions
47 lines (40 loc) · 1.09 KB
/
JosephusProblem1.java
File metadata and controls
47 lines (40 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.io.*;
import java.lang.StringBuilder;
import java.util.*;
class Node {
Node next;
int data;
Node(int data) {
this.data = data;
}
}
class JosephusProblem1{
public static void main(String []args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Node curr = new Node(1);
StringBuilder ans = new StringBuilder();
Node head = curr;
for(int i = 2; i <= n; i++) {
Node temp = new Node(i);
curr.next = temp;
curr = temp;
}
curr.next = head;
Node pre = curr;
curr = head;
int count = n;
while(count != 1) {
pre = curr;
curr = curr.next;
ans.append(curr.data);
ans.append(" ");
pre.next = curr.next;
curr = pre.next;
count--;
}
ans.append(curr.data);
System.out.println(ans.toString());
}
}