Implement stack using Linked List in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this program, we will see how to implement stack using Linked List in java.
Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using Linked List.
There are two most important operations of Stack:
  • Push : We will push element to beginning of linked list to demonstrate push behavior of  stack.
  • Pop : We will remove first element of linked list to demonstrate pop behavior of Stack .

Java Program:

Lets create a java program to create stack using Linked List.
package org.arpit.java2blog;

public class LinkedListStack {
 private Node head; // the first node

 // nest class to define linkedlist node
 private class Node {
  int value;
  Node next;

 public LinkedListStack() {
  head = null;

 // Remove value from the beginning of the list for demonstrating behaviour of stack
 public int pop() throws LinkedListEmptyException {
  if (head == null) {
   throw new LinkedListEmptyException();
  int value = head.value;
  head =;
  return value;

 // Add value to the beginning of the list for demonstrating behaviour of stack
 public void push(int value) {
  Node oldHead = head;
  head = new Node();
  head.value = value; = oldHead;

 public static void main(String args[]) 
  LinkedListStack lls=new LinkedListStack();
           System.out.println("Element removed from LinkedList: "+lls.pop());
           System.out.println("Element removed from LinkedList: "+lls.pop());
           System.out.println("Element removed from LinkedList: "+lls.pop());
  public static void printList(Node head) {
    Node temp = head;
    while (temp != null) {
     System.out.format("%d ", temp.value);
     temp =;

 * Exception to indicate that LinkedList is empty.

class LinkedListEmptyException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public LinkedListEmptyException() {

 public LinkedListEmptyException(String message) {
When you run above program, you will get below output:
Element removed from LinkedList: 75
Element removed from LinkedList: 60
Element removed from LinkedList: 10
40 80 50 20 

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012