Java: LinkedList class as stack and queues

11,760

Solution 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 LIFO (Last in first out) data structure.

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

Share:
11,760
Anonymous
Author by

Anonymous

Updated on June 15, 2022

Comments

  • Anonymous
    Anonymous almost 2 years

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