-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathTrainComposition.java
36 lines (29 loc) · 1.08 KB
/
TrainComposition.java
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
package by.andd3dfx.common;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* A TrainComposition is built by attaching and detaching wagons from the left and the right sides.
* <p>
* For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get
* a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7
* and the first that can be detached from the left is 13.
* <p>
* Implement a TrainComposition that models this problem.
*
* @see <a href="https://youtu.be/ToXzQU6vIKw">Video solution</a>
*/
public class TrainComposition {
private Deque<Integer> deque = new ArrayDeque<>();
public void attachWagonFromLeft(int wagonId) {
deque.addFirst(wagonId);
}
public void attachWagonFromRight(int wagonId) {
deque.addLast(wagonId);
}
public int detachWagonFromLeft() {
return deque.removeFirst();
}
public int detachWagonFromRight() {
return deque.removeLast();
}
}