Write a Java program to use LinkedList as Stack(LIFO)


The LinkedList_Stack class contains a main method where a LinkedList object named st is created and populated with string elements using the add method. The System.out.println statement is used to print the initial state of the st linked list, which represents the elements in the stack.

The st.pop() method is called twice to simulate popping elements from the stack. The pop() method removes and returns the first element (head) of the linked list, which represents the top element of the stack. The popped elements are printed using the System.out.print statement. Finally, the System.out.println statement is used to print the state of the st linked list after popping elements from the stack.

Note: In this example, pop() method is used to demonstrate the concept of stack, but it is not a standard method of LinkedList class. To use a LinkedList as a stack, you can use the push() method to add elements to the front (head) of the linked list, and use the pop() method to remove elements from the front (head) of the linked list, which represents the top of the stack.

Source Code

import java.util.*;
public class LinkedList_Stack
{
	public static void main(String[] args)
	{
		LinkedList<String> st = new LinkedList<String>(); 
		st.add("JAVA"); 
		st.add("CPP"); 
		st.add("PYTHON"); 
		st.add("RUBY"); 
		st.add("PHP"); 
		st.add("C"); 
		st.add("MYSQL"); 
		st.add("C#.NET");
 
		System.out.println("Given LinkedList : "+st);
		System.out.print("Poping out the elements from the stack : "+st.pop()+" , "+st.pop());
		System.out.println("\nAfter LinkedList : "+st);
	}
}

Output

Given LinkedList : [JAVA, CPP, PYTHON, RUBY, PHP, C, MYSQL, C#.NET]
Poping out the elements from the stack : JAVA , CPP
After LinkedList : [PYTHON, RUBY, PHP, C, MYSQL, C#.NET]

Example Programs