简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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