Description
Programs to demonstrate push and pop operations on LinkedList.
LinkedList.push(E e)
public void push(E e)
: Inserts the element at the front of the list.
Example:
import java.util.LinkedList; class LinkedListExample { public static void main(String[] args) { // Create a LinkedList of Strings LinkedList<String> list = new LinkedList<String>(); // Add few Elements list.add("Jack"); list.add("Robert"); list.add("Chaitanya"); list.add("kate"); // Display LinkList elements System.out.println("LinkedList contains: "+list); // push Element the list list.push("NEW ELEMENT"); // Display after push operation System.out.println("LinkedList contains: "+list); } }
Output:
LinkedList contains: [Jack, Robert, Chaitanya, kate] LinkedList contains: [NEW ELEMENT, Jack, Robert, Chaitanya, kate]
LinkedList.pop()
public E pop()
: Removes and returns the first element of the list.
Example:
import java.util.LinkedList; class LinkedListPopDemo{ public static void main(String[] args) { // Create a LinkedList of Strings LinkedList<String> list = new LinkedList<String>(); // Add few Elements list.add("Jack"); list.add("Robert"); list.add("Chaitanya"); list.add("kate"); // Display LinkList elements System.out.println("LinkedList before: "+list); // pop Element from list and display it System.out.println("Element removed: "+list.pop()); // Display after pop operation System.out.println("LinkedList after: "+list); } }
Output:
LinkedList before: [Jack, Robert, Chaitanya, kate] Element removed: Jack LinkedList after: [Robert, Chaitanya, kate]
Leave a Reply