【Java】队列和栈

文章探讨了如何使用双向链表和单向链表来设计队列。双向链表可实现双端队列,允许在两端进行插入和删除操作。单向链表通过特定的头插尾删方法也能实现队列功能。文章详细比较了add、offer、remove、poll、element和peek等方法在不同链表结构下的行为差异,特别是在队列为空或满时的情况。
摘要由CSDN通过智能技术生成

可以使用双向链表进行设计一个队列,也可以使用单向链表设计一个队列

双向链表

可以实现成为双端队列,即一个队列的队头也可以成为这个队列的队尾。

单向链表

如果使用头插,尾删的方法(头删,尾插)可以实现

方法中的异同:

add()

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add, which can fail to insert an element only by throwing an exception.

立即插入元素,如果容量满,抛出异常,

offer()

Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.

返回队头元素并将其删除,如果队列为空将抛出异常。

remove()

Retrieves and removes the head of this queue, or returns null if this queue is empty.

返回队头元素并将其删除,如果队列为空则返回null。

poll()

Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.

返回队头元素,如果队列为空将抛出异常。

element()

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

返回队头元素,如果队列为空将抛出异常。

peek()

返回队头元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值