LinkedList push and pop methods
Adding and removing element in LinkedList can also be done by push and pop methods.
1. void push(E e) – Adds an element into the List as the first element
2. E pop() – Removes the first element of the list.
Lets see some examples on LinkedList push and pop methods.
LinkedList push and pop methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package com.kscodes.collections.linkedList; import java.util.LinkedList; public class LinkedListPushPop { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // Use add(E e) to add elements linkedList.add("Java"); linkedList.add("JSP"); linkedList.add("Spring MVC"); System.out.println("****LinkedList elements :: " + linkedList.toString()); // Use push to add one more element. // This will get added at the top - as first element linkedList.push("Hibernate"); System.out.println("****LinkedList elements after push :: " + linkedList.toString()); // Use pop to remove a element // This will remove the first element - "Hibernate" linkedList.pop(); System.out.println("****LinkedList elements after pop :: " + linkedList.toString()); } } |
Output
1 2 3 | ****LinkedList elements :: [Java, JSP, Spring MVC] ****LinkedList elements after push :: [Hibernate, Java, JSP, Spring MVC] ****LinkedList elements after pop :: [Java, JSP, Spring MVC] |