Skip to content

Java LinkedList Add Element at Beginning Example

This example shows how to add an element at the beginning of the LinkedList (front) in Java. The example also shows how to insert an element at any index of the LinkedList.

How to add an element at the beginning of the LinkedList (at the front)?

1. Using the add method

When you add an element to the LinkedList using the add method, by default it is appended at the end of the LinkedList object. What if you want to add an element at the beginning of the LinkedList or at the front of the LinkedList?

Well, in that case, you can use the overloaded add method that also accepts the index argument.

This add method adds the specified element at the specified index in the LinkedList object. It also shifts any element located at the current position and all other subsequent elements to the right by increasing their indices by 1.

In order to add the element at the beginning, we need to call this method with index 0 as given below.

Output

As you can see from the output, the element “Yellow” is inserted at the front i.e. index 0 and all the current subsequent element’s indices are increased by 1 thus shifting them to the right.

2. Using the addFirst method

You can also use the addFirst method declared in the Deque interface to add an element at the front of the LinkedList object.

Output

How to insert an element at the specified index in the LinkedList?

Specify the index at which you want to insert an element in the LinkedList in the add method. All the existing elements will be shifted to the right by the add method automatically.

The below given example inserts the “Black” element at index 1 of the LinkedList object.

Output

As you can see from the output, the “Black” element is inserted at index 1 and the index of the “Green” and “Blue” elements have been increased to 2 and 3 respectively.

This example is a part of the Java LinkedList tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.