Created
January 29, 2019 08:01
-
-
Save vignarajj/c789963a4097cb7228405582dc1d990d to your computer and use it in GitHub Desktop.
TrainComposition Solution in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package javaproblems; | |
import java.util.Deque; | |
import java.util.LinkedList; | |
public class TrainComposition { | |
private final Deque<Integer> wagons = new LinkedList<>(); | |
public void attachWagonFromLeft(int wagonId) { | |
wagons.addFirst(wagonId); | |
} | |
public void attachWagonFromRight(int wagonId) { | |
wagons.addLast(wagonId); | |
} | |
public int detachWagonFromLeft() { | |
if(!wagons.isEmpty()){ | |
return wagons.removeFirst(); | |
}else{ | |
return -1; | |
} | |
} | |
public int detachWagonFromRight() { | |
if(!wagons.isEmpty()){ | |
return wagons.removeLast(); | |
}else{ | |
return -1; | |
} | |
} | |
public static void main(String[] args) { | |
TrainComposition tree = new TrainComposition(); | |
tree.attachWagonFromLeft(7); | |
tree.attachWagonFromLeft(13); | |
System.out.println(tree.detachWagonFromRight()); // 7 | |
System.out.println(tree.detachWagonFromLeft()); // 13 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment