LinkedList - push() and pop() methods in Java

The LinkedList data collection is represented by a stack in the system. To stack and unstack, LinkedList has two methods: push and pop. This example shows how to call the push() and pop() methods on LinkedList.

public void push(Object o): Inserts an element into the stack header of LinkedList.

Example:

import java.util.LinkedList; 

public class PushPop {

public static void main(String[] args) {

LinkedList llist = new LinkedList();

llist.add("e1");
llist.add("e2");
llist.add("e3");

System.out.println(llist);

llist.push("New Element");

System.out.println(llist);
}
}
Output:

[e1, e2, e3]
[New element, e1, e2, e3]
public void pop(): Removes the first element of the stack header from LinkedList.

import java.util.LinkedList; 

public class PushPop {

public static void main(String[] args) {

LinkedList llist = new LinkedList();

llist.add("e1");
llist.add("e2");
llist.add("e3");

System.out.println(llist);

llist.pop();

System.out.println(llist);
}
}
Output:

[e1, e2, e3]
[e2, e3]
The deleted item is: e1.

As a conclusion, we can say that the use of push() and pop() is favorable when you want to add an element to the first position or remove the first element from LindekList.
Advertisement

AdBlock Detected

Please disable your ad blocker and refresh the window to use this website.