public static Deque<BuildingWithHeight> examineBuildingsWithSunset(
Iterator<Integer> sequence) {
int buildingIdx = 0;
Deque<BuildingWithHeight> buildingsWithSunset = new LinkedList<>();
while (sequence.hasNext()) {
Integer buildingHeight = sequence.next();
while (!buildingsWithSunset.isEmpty()
&& (Integer.compare(buildingHeight,
buildingsWithSunset.**peekFirst**().height)
>= 0)) {
buildingsWithSunset.**removeFirst**();
}
buildingsWithSunset.**addFirst**(
new BuildingWithHeight(buildingIdx++, buildingHeight));
}
return buildingsWithSunset;
}
The difference from the book’s solution is that the elements in the returned dequeue is in reversed order, which i think is ok. I just wanted the methods to be strictly consistent with the stack operations, i.e., it returns exactly same result as when we use the peek(), push() and pop() methods.