Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

LinkedList removeFirst method in Java

Last Updated on December 13, 2022 by Prepbytes

Introduction

The linked list is one of the most important data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

Problem Statement

The LinkedList removeFirst() method is an important concept when it comes to Linked List problems. This method removes the head of the linked list and also returns it after removing it.

Problem Statement Understanding

Let’s try to understand this removeFirst() method with help of an example.

Suppose the given list is:

When we use the removeFirst() method, this method returns the head of the linked list. After returning the head, this method deletes it from the list.

So, on applying the above operations on the given list, we will get:

  • Coding in output, as it is the head of the linked list, and the final linked list will now be:

Input:

Output: Coding

Explanation: As we can see, the first element (Coding) is printed.

This concept is not a very complex one. We have to just use the removeFirst() method on the given linked list whenever we want to remove the head from the linked list. Let us have a glance at the approach and algorithm.

Approach and Algorithm

The approach is going to be pretty simple. We will create a new LinkedList and add elements to it. Then, we will just use the list.removeFirst(), it will return the head of the linked list and will also delete it from the linked list. Now, we can simply use the content of head returned by removeFirst() method.

Dry Run

Code Implementation

import java.io.*;
import java.util.LinkedList;

public class LinkedListDemo {
    public static void main(String args[])
    {

        LinkedList<string> list = new LinkedList<string>();

        list.add("Coding");
        list.add("is");
        list.add("fun");


        System.out.println("LinkedList:" + list);

        System.out.println("The first element is: " + list.removeFirst());

        System.out.println("Final LinkedList:" + list);
    }
}

Output

LinkedList: [Coding, is, Fun]
The first element is: Coding
Final LinkedList: [is, Fun]

Time Complexity: O(1), as constant work is being done.
[forminator_quiz id=”3900″]

So, in this article, we have tried to explain how to use LinkedList removeFirst() method in Java. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

Leave a Reply

Your email address will not be published. Required fields are marked *