we use a deque to act as a doubly linked list as both stack and queue
there is actually deque in java too that can be implemented as a linkedlist like this
import java.util.Deque;
import java.util.LinkedList;
public class TrainComposition {
private Deque<Integer> deque;
public TrainComposition() {
deque = new LinkedList<>();
}
public void attachWagonFromLeft(int wagonId) {
deque.addFirst(wagonId);
}
public void attachWagonFromRight(int wagonId) {
deque.addLast(wagonId);
}
public int detachWagonFromLeft() {
if (!deque.isEmpty()) {
return deque.removeFirst();
} else {
throw new IllegalStateException("Train composition is empty");
}
}
public int detachWagonFromRight() {
if (!deque.isEmpty()) {
return deque.removeLast();
} else {
throw new IllegalStateException("Train composition is empty");
}
}