简体   繁体   English

Deque 接口中的 addFirst 和 addLast 有什么区别

[英]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.它们似乎以相同的方式表现,以 LIFO 模式抛出元素。

   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,打印出: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,打印出:10,9,8,7,6,5,4,3,2,1,0,

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: deque 中的 addFirst 意味着它将在第一个 position 处添加每个元素,例如:假设有一个名为“number”的变量,并且 number 中有 3 个元素:

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. output 将类似于 [7,10,9,8] 并且在 addLast 中相同,它将在列表的最后添加元素。

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在第二种情况下,您从最后一个到第一个打印它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM