Java 5 – Queue’s push and pop operations with LinkedList

In this article, we will discuss how to perform push and pop operations with LinkedList

1. LinkedList and Deque :

  • From Java 1.5 version, after collection framework restructuring LinkedList class also implements Deque/Queue interface
  • in addition to List interface
  • LinkedList based implementation of queue interface follows First-In First-Out (FIFO)
  • So, from Java 1.6 version Deque interface’s, push/pop operations are available to LinkedList class

2. Push and Pop operation with LinkedList :

  • push() –> pushes an element onto stack represented by list i.e.; inserts element at front of list
  • pop() –> pops an element from stack represented by list i.e.; removes/returns first element of list

LinkedListPushAndPopOperations.java

package in.bench.resources.java.collections;

import java.util.LinkedList;

public class LinkedListPushAndPopOperations {

	public static void main(String[] args) {

		// creating LinkedList object of type String
		LinkedList<String> ll = new LinkedList<String>();

		// adding elements to LinkedList object
		ll.add("Sun");
		ll.add("Apple");
		ll.add("JBoss");
		ll.add("Whatsup");
		ll.add("Android");
		ll.add("BEA Weblogic");
		ll.add("Apache");

		// Iterating using enhanced for-loop
		System.out.println("LinkedList as per Insertion Order:\n");
		for(String str : ll) {
			System.out.println(str);
		}

		// push operation with LL
		ll.push("Google");

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating after pushing\n");
		for(String str : ll) {
			System.out.println(str);
		}

		// pop operation with LL
		String poppedString = ll.pop();

		System.out.println("\n\nPopped element : " + poppedString);

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating after popping\n");
		for(String str : ll) {
			System.out.println(str);
		}
	}
}

Output:

LinkedList as per Insertion Order:

Sun
Apple
JBoss
Whatsup
Android
BEA Weblogic
Apache

Iterating after pushing

Google
Sun
Apple
JBoss
Whatsup
Android
BEA Weblogic
Apache

Popped element : Google

Iterating after popping

Sun
Apple
JBoss
Whatsup
Android
BEA Weblogic
Apache

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to remove duplicate elements from ArrayList maintaining insertion-order ?
Java - LinkedList specific method examples