LinkedList push() Method in Java

The java.util.LinkedList.push() method is used to push an element at the starting(top) of the stack represented by LinkedList. This is similar to the addFirst() method of LinkedList and simply inserts the element at the first position or top of the linked list.

Syntax:

LinkedListObject.push(Object element)

Parameters: The method accepts one parameter element of object type and represents the element to be inserted. The type ‘Object’ should be of same Stack represented by the LinkedList.

Return Type: The return type of the method is void i.e. it doesn’t returns any value.



Below programs illustrate the java.util.LinkedList.push() method:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate push() method
import java.util.LinkedList;
  
public class GfG {
    // Main method
    public static void main(String[] args)
    {
  
        // Creating a LinkedList object to represent a stack.
        LinkedList<String> stack = new LinkedList<>();
  
        // Pushing an element in the stack
        stack.push("I");
  
        // Pushing an element in the stack
        stack.push("Like");
  
        // Pushing an element in the stack
        stack.push("GeeksforGeeks");
  
        // Printing the complete stack.
        System.out.println(stack);
    }
}

chevron_right


Output:

[GeeksforGeeks, Like, I]

Program 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate push() method
  
import java.util.LinkedList;
  
public class GfG {
    // main method
    public static void main(String[] args)
    {
  
        // Creating a LinkedList object to represent a stack.
        LinkedList<Integer> stack = new LinkedList<>();
  
        // Pushing an element in the stack
        stack.push(30);
  
        // Pushing an element in the stack
        stack.push(20);
  
        // Pushing an element in the stack
        stack.push(10);
  
        // Printing the complete stack.
        System.out.println(stack);
    }
}

chevron_right


Output:

[10, 20, 30]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.