If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.
In this program, we will see how to implement stack using Linked List in java.
The Stack
is an abstract data type that demonstrates Last in first out (LIFO
) behavior. We will implement the 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
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 = head.next; 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; head.next = oldHead; } public static void main(String args[]) { LinkedListStack lls=new LinkedListStack(); lls.push(20); lls.push(50); lls.push(80); lls.push(40); lls.push(60); lls.push(75); System.out.println("Element removed from LinkedList: "+lls.pop()); System.out.println("Element removed from LinkedList: "+lls.pop()); lls.push(10); System.out.println("Element removed from LinkedList: "+lls.pop()); printList(lls.head); } public static void printList(Node head) { Node temp = head; while (temp != null) { System.out.format("%d ", temp.value); temp = temp.next; } System.out.println(); } } /** * * Exception to indicate that LinkedList is empty. */ class LinkedListEmptyException extends RuntimeException { private static final long serialVersionUID = 1L; public LinkedListEmptyException() { super(); } public LinkedListEmptyException(String message) { super(message); } } |
Element removed from LinkedList: 75
Element removed from LinkedList: 60
Element removed from LinkedList: 10
40 80 50 20
Element removed from LinkedList: 60
Element removed from LinkedList: 10
40 80 50 20
That’s all about implement stack using Linked List in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.