'What is the difference between addFirst and addLast in Deque interface
They seem like behaving in the same way, throwing out the elements in a LIFO pattern.
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= 10; i++) {
stack.addFirst(i);
}
while(!stack.isEmpty()) {
System.out.print(stack.removeFirst()+",");
}
Prints out : 10,9,8,7,6,5,4,3,2,1,0,
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= 10; i++) {
stack.addLast(i);
}
while(!stack.isEmpty()) {
System.out.print(stack.removeLast()+",");
}
Prints out : 10,9,8,7,6,5,4,3,2,1,0,
Solution 1:[1]
addFirst in deque means that it will be adding every element at the first position like: lets say there is a variable named "number" and number has 3 elements in it:
number = [10,9,8]
// if i add 7 in it
number = addFirst(7)
output will be like [7,10,9,8] and same in addLast it will add element at the last of the list.
Solution 2:[2]
It's is due to your print method being different.
stack.removeFirst()
// ...
stack.removeLast()
On the first case you print them from first to last
On the second case you print them from last to first
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sarim Sikander |
| Solution 2 | IQbrod |
