简体   繁体   English

Java:LinkedList类作为堆栈和队列

[英]Java: LinkedList class as stack and queues

I am new to LinkedList class, and facing difficulties as to how to use it in order to implement or instantiate stack and queues object. 我是LinkedList类的新手,并且在如何使用它以实现或实例化堆栈和队列对象方面面临困难。 I am not looking for piece of self-implemented codes. 我不是在寻找一段自行实现的代码。

I wanted to know how do we use this class as stack and queues and can use the already defined methods: pop,push,enqueue and dequeue or top (in case of stacks). 我想知道我们如何将这个类用作堆栈和队列,并且可以使用已经定义的方法:pop,push,enqueue和dequeue或top(在堆栈的情况下)。

Queue 队列

A LinkedList is already a queue, since it implements the Queue interface (and check the Javadoc yourself). LinkedList已经是一个队列,因为它实现了Queue接口(并自己检查Javadoc )。 Hence it has the following queue operations: 因此它具有以下队列操作:

enqueue: 排队:

add() - Appends the specified element to the end of this list.

dequeue: 出队:

remove() - Retrieves and removes the head (first element) of this list.

Stack

It is also very easy to use a LinkedList as a stack, since it has a method removeLast() which can remove an item from the end of the list (rather than the start, which remove() does: 使用LinkedList作为堆栈也很容易,因为它有一个方法removeLast() ,它可以从列表的末尾删除一个项目(而不是start, remove()

push: 推:

add() - Appends the specified element to the end of this list.

pop: 流行:

removeLast() - Removes and returns the last element from this list.

Appending and removing always from the end of the list simulates a stack, which is a FIFO (first in first out) data structure. 始终从列表末尾追加和删除模拟堆栈,该堆栈是FIFO(先进先出)数据结构。

If you take a look at the implemented interfaces, then LinkedList is a drop-in implementation for queues. 如果您查看已实现的接口,则LinkedList是队列的插入式实现。

Stack is not an interface in java, but a class. Stack不是java中的接口,而是一个类。 LinkedList doesn't contain the peek() , empty() and search() methods, so it's not a fully-fledged stack. LinkedList不包含peek()empty()search()方法,因此它不是一个完全成熟的堆栈。 Still, it can be useful. 不过,它可能很有用。

I know this is an old post, but it bit me. 我知道这是一个老帖子,但它咬了我一下。 But i also caution replacement of a Stack. 但我也提醒更换Stack。 While some, like LinkedList, provide push, pop, and peak - the items are placed in the list in different order. 虽然像LinkedList这样的一些提供了push,pop和peak - 但是这些项目以不同的顺序放在列表中。 LinkedList works off the front end, Stack works off the back. LinkedList在前端工作,Stack在后面工作。 So, if iterating the list, they are reversed. 因此,如果迭代列表,它们将被颠倒。 so be careful ... 所以要小心......

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

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