LinkedList push() Method in Java

Introduction

One of the most crucial data structures to learn while preparing for interviews is the linked list. In a coding interview, having a thorough understanding of Linked Lists might be a major benefit.

The java.util.LinkedList.push() function is basically used to push an element to the top (beginning) of the stack which is represented by a linked list. This is similar to LinkedList's addFirst() function, and it simply puts the element at the first position or top of the linked list.

push() Method

Syntax: LinkedListObject.push(Object x)

Parameters: The function takes parameter an object type element that represents the element to be added. The type of Object should be the same as that of the stack, represented by a LinkedList.

Return Value: It has a void return type.

This method pushes the element passed as a parameter to the top of the stack represented by a linked list. We will just call the push(Object X) method.

Input

Empty List, Elements to be pushed: Coding, is, Fun

Output

[Fun, is, Coding]

Explanation
  • First, Coding was added to the top of the empty list.
  • Then, is was added to the top of the list.
  • Then, finally, Fun was added to the top of the list.

Code Implementation

import java.util.LinkedList;
  
public class PrepBytes {
    public static void main(String[] args)
    {

        LinkedList llst = new LinkedList<>();
 
        llst.push("Coding");
 
        llst.push("is");

        llst.push("Fun");

        System.out.println(llst);
    }
}
Output

[Fun, is, Coding]

Time Complexity: O(1), as the new element gets added to the top of the list, i.e., no list traversal is needed.

So, in this article, we have tried to explain the most efficient way to implement the LinkedList push() Method in Java. Java Collection Framework is very important when it comes to coding interviews. 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.

Previous post How to get a Sublist of LinkedList in Java
Next post Recursive selection sort for singly linked list | Swapping node links

Leave a Reply

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