-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBallpassing.java
More file actions
98 lines (85 loc) · 1.82 KB
/
Ballpassing.java
File metadata and controls
98 lines (85 loc) · 1.82 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Name : Yu Chenghui
* Matric. No : A0194474U
* PLab Acct. :
*/
import java.util.*;
public class Ballpassing {
// attributes
public int size = 0;
public Node head = null;
public Node tail = null;
private void run() {
// read initial students
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for (int i = 0; i < N; i++) {
String student = sc.next();
addNodeToTail(student);
}
int Q = sc.nextInt();
// j keeps track of the pointer
int j = 0;
// n keeps track of the total number of students
int n = N;
// every step
for (int i = 0; i < Q; i++) {
// read event
String event = sc.next();
if (event.equals("NEXT")) {
// next
System.out.println(head.next.element);
head = head.next;
tail = tail.next;
} else if (event.equals("LEAVE")) {
// leave
System.out.println(head.next.element);
removeNodeFromHead();
} else {
// join
String newStudent = sc.next();
addNodeAfterHead(newStudent);
}
}
}
class Node {
String element;
Node next;
public Node(String element) {
this.element = element;
}
}
public void addNodeToTail(String element) {
Node node = new Node(element);
if (size == 0) {
head = node;
tail = node;
node.next = head;
} else {
tail.next = node;
tail = node;
tail.next = head;
}
size++;
}
public void addNodeAfterHead(String element) {
System.out.println(element);
Node node = new Node(element);
Node temp = head.next;
head.next = node;
head.next.next = temp;
head = head.next;
tail = tail.next;
size++;
}
public void removeNodeFromHead() {
Node temp = head.next;
tail.next = temp;
head = temp;
size--;
}
public static void main(String[] args) {
Ballpassing newBallpassing = new Ballpassing();
newBallpassing.run();
}
}