In previous post Stack implementation in Java using array we learned how to implement Stack using array. In this post we will learn How to Implement Stack in java using Linked List ?
Below Is the complete source code:
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 |
package com.kkjavatutorials.stack; import java.util.EmptyStackException; public class Stack { private Node top; private int size; private class Node{ private int data; private Node next; public Node(int data) { this.data = data; this.next = null; } } public void push(int data) { Node tempNode = new Node(data); tempNode.next = top; top = tempNode; size++; } public int pop() { if(isEmpty()) { throw new EmptyStackException(); } int result = top.data; top = top.next; size--; return result; } public int peek() { if(isEmpty()) { throw new EmptyStackException(); } return top.data; } public int size(){ return size; } public boolean isEmpty() { return size == 0; } public void displayStack() { Node current = top; while (current != null) { System.out.print(current.data+" "); current = current.next; } } } |
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 |
package com.kkjavatutorials.client; import com.kkjavatutorials.stack.Stack; public class ClientTest { public static void main(String[] args) { Stack stack = new Stack(); System.out.println(stack.size()); stack.push(10); stack.push(20); stack.push(30); stack.push(40); stack.push(50); stack.push(60); System.out.println(stack.size()); System.out.println(stack.isEmpty()); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.size()); } } |
Output of the above program:
0
6
false
60
60
5
You May Also Like:
Which data type would you choose for storing currency values like Trading Price in Java?
How would you print a given currency value for Indian Locale (INR Currency)?
Which classes in java are immutable ?
How would you round a double value to certain decimal Precision and Scale ?
What is BlockingQueue? How can we implement Producer and Consumer problem using Blocking Queue?
How to get number of available processors in Java ?
That’s all about How to Implement Stack in java using Linked List ?
If you have any feedback or suggestion please feel free to drop in below comment box.