Write a Java program to pop items from the stack represented by the LinkedList


The code demonstrates how to use the push and pop methods of LinkedList in Java to add items to the beginning of the list and remove items from the beginning of the list, respectively.

In the Pop_Items class, a LinkedList object named bk is created with a type parameter , indicating that it will hold only string items. Several string items, including "CPP", "JAVA", "PYTHON", "C", "RUBY", and "C#.NET", are added to the bk list using the push method, which adds items to the beginning of the list.

The System.out.println statements are used to print the items removed from the bk list using the pop method. The pop method removes and returns the first item (i.e., the item at the beginning) of the list. Note that the items are printed in the reverse order they were added, since pop removes items from the beginning of the list. If the list is empty, pop returns null.

Please note that using push and pop methods on a LinkedList can result in poor performance for large lists, as adding or removing items from the beginning of the list requires shifting all the subsequent items, resulting in an O(n) time complexity operation. For better performance, consider using a Deque implementation, such as ArrayDeque, which provides efficient addFirst, removeFirst, addLast, and removeLast methods to add and remove items from both ends of the list in constant time.

Source Code

import java.util.LinkedList;
public class Pop_Items
{
	public static void main(String[] args)
	{
		LinkedList <String> bk = new LinkedList <String> ();
		bk.push("CPP");
		bk.push("JAVA");
		bk.push("PYTHON");
		bk.push("C");
		bk.push("RUBY");
		bk.push("C#.NET");
 
		System.out.println(bk.pop());
		System.out.println(bk.pop());
		System.out.println(bk.pop());
		System.out.println(bk.pop());
		System.out.println(bk.pop());
		System.out.println(bk.pop());
	}
}

Output

C#.NET
RUBY
C
PYTHON
JAVA
CPP

Example Programs