Java: LinkedList class as stack and queues

佐手、 提交于 2020-06-25 21:48:38

问题


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. 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).


回答1:


Queue

A LinkedList is already a queue, since it implements the Queue interface (and check the Javadoc yourself). 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:

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.




回答2:


If you take a look at the implemented interfaces, then LinkedList is a drop-in implementation for queues.

Stack is not an interface in java, but a class. LinkedList doesn't contain the peek(), empty() and search() methods, so it's not a fully-fledged stack. Still, it can be useful.




回答3:


I know this is an old post, but it bit me. But i also caution replacement of a Stack. While some, like LinkedList, provide push, pop, and peak - the items are placed in the list in different order. LinkedList works off the front end, Stack works off the back. So, if iterating the list, they are reversed. so be careful ...



来源:https://stackoverflow.com/questions/38591371/java-linkedlist-class-as-stack-and-queues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!