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:
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.
public void push(Object o): Inserts an element into the stack header of LinkedList.
Example:
import java.util.LinkedList;Output:
public class PushPop {
public static void main(String[] args) {
LinkedListllist = new LinkedList ();
llist.add("e1");
llist.add("e2");
llist.add("e3");
System.out.println(llist);
llist.push("New Element");
System.out.println(llist);
}
}
[e1, e2, e3]public void pop(): Removes the first element of the stack header from LinkedList.
[New element, e1, e2, e3]
import java.util.LinkedList;Output:
public class PushPop {
public static void main(String[] args) {
LinkedListllist = new LinkedList ();
llist.add("e1");
llist.add("e2");
llist.add("e3");
System.out.println(llist);
llist.pop();
System.out.println(llist);
}
}
[e1, e2, e3]The deleted item is: e1.
[e2, e3]
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.