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).
In general, Stacks and Queues can be implemented using Arrays and Linked Lists . The reason you would use Linked List for implementing Stack is when you need a functionality involving LAST IN FIRST OUT form and you are not sure how many elements that functionality requires.
A stack can be implemented using a LinkedList by managing the LinkedList as a stack. This is done by using a class Stack which contains some of the Stack methods such as push(), top(), pop() etc.
The difference between stacks and queues is how they are removed. In a stack, we remove the item most recently added; in a queue, we remove the item least recently added. There are many ways to implement a queue data structure, but we are going to do it using a linked list.
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.
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 LIFO (Last 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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With