Queue, Stack and Deque

Queue, Stack and Deque

队列:先进先出 FIFO
在这里插入图片描述

enqueue: 进队
dequeue: 出队

复杂度

In case of using a linked list or a classic array (non-resizable) as an internal structure

进队和出队的复杂度都为常数 O(1),不取决于队中有多少个Element。因此非常快。

Java中队列由Queue接口表示,扩展了Collection,添加了新方法,

  1. boolean offer(E e),插入element到队列,返回true / false。(根据队列容量),
  2. add(E e),同offer,但容量满时,会抛出错误
  3. E poll(),返回第一个元素,并在队列中删除,队列为空,返回null
  4. E remove(),同poll,但但容量为空时会抛出错误
  5. E element(),返回第一个元素,但不删除,容量为空时,抛出错误。
  6. E peek(),返回第一个元素,但不删除,容量为空时,返回null
建议使用:offer, peek, poll

在这里插入图片描述
Collection, Queue, Deque为Interface; PriorityQueue, LinkedList, ArrayDeque, Stack为Class。

对于处理大量元素而言,由于不需要为每个元素创建内部节点,因此ArrayDeque内存使用效率比LinkedList更高
在这里插入图片描述

使用ArrayDeque作为队列
Queue<String> q = new ArrayDeque<>();
 
q.offer("first");
q.offer("second");
q.offer("third");
 
System.out.println(q.peek()); // first
System.out.println(q.peek()); // first
System.out.println(q.poll()); // first,
 
System.out.println(q.peek()); // second
System.out.println(q.poll()); // second
System.out.println(q.poll()); // third
 
System.out.println(q.isEmpty()); // true

由于 ArrayDeque并LinkedList实现了此接口,因此它们都可以充当队列(FIFO),堆栈(LIFO)或双端队列。

使用Deque作为Stack

Deque<String> stack = new ArrayDeque<>();
 
stack.offerLast("first");
stack.offerLast("second");
stack.offerLast("third");
 
System.out.println(stack); // [first, second, third]
 
System.out.println(stack.pollLast()); // third
System.out.println(stack.pollLast()); // second
System.out.println(stack.pollLast()); // first
 
System.out.println(stack.pollLast()); // null

建议使用这种,后面有Stack作为Stack的,不推荐

Stack

在这里插入图片描述

现实中例子书籍堆放

复杂度

与Queue一样

Stack<String> stack = new Stack<>();
 
stack.push("first");
stack.push("second");
stack.push("third");
 
System.out.println(stack); // [first, second, third]
 
System.out.println(stack.pop()); // "third"
System.out.println(stack.pop()); // "second"
System.out.println(stack.pop()); // "first"
 
System.out.println(stack.pop()); // throws EmptyStackException

pop()如果堆栈为空,则抛出错误。建议使用ArrayDeque.

Deque

双端队列:将队列FIFO和stack的LIFO访问规则组合在了一起。可以在两端进行插入和取出。
在这里插入图片描述

remove an element from the front
remove an element from the front
remove an element from the front
insert 20 to the front
remove an element from the back
remove an element from the back
insert 30 to the back

进行上述操作后,得到结果

在这里插入图片描述

Deque总结

通常,deque会有附加操作允许我们看见头尾元素。deque不支持indexing访问。但能通过一些Implementations实现。
如果想实现Queue (FIFO): offerLast; pollFirst;
如果想实现Stack (LIFO): offerLast; pollLast;

stack, queue和deque都无法通过index进行取值,只关注首尾元素。复杂度为O(1).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值