Java Program to Implement Stack using Linked List

This is a Java Program to implement a stack using linked list. Stack is an area of memory that holds all local variables and parameters used by any function, and remembers the order in which functions are called so that function returns occur correctly. Each time a function is called, its local variables and parameters are “pushed onto” the stack. When the function returns, these locals and parameters are “popped”. Because of this, the size of a program’s stack fluctuates constantly as the program is running, but it has some maximum size. Stack is a Last In First Out (LIFO) abstract data type and linear data structure. Linked list is a data structure consisting of a group of nodes which together represent a sequence. Here we need to apply the application of linked list to perform basic operations of stack.

Here is the source code of the Java program to implement stack using linked list. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  * Java Program to Implement Stack using Linked List
  3.  */
  4.  
  5. import java.util.*;
  6.  
  7. /*  Class Node  */
  8. class Node
  9. {
  10.     protected int data;
  11.     protected Node link;
  12.  
  13.     /*  Constructor  */
  14.     public Node()
  15.     {
  16.         link = null;
  17.         data = 0;
  18.     }    
  19.     /*  Constructor  */
  20.     public Node(int d,Node n)
  21.     {
  22.         data = d;
  23.         link = n;
  24.     }    
  25.     /*  Function to set link to next Node  */
  26.     public void setLink(Node n)
  27.     {
  28.         link = n;
  29.     }    
  30.     /*  Function to set data to current Node  */
  31.     public void setData(int d)
  32.     {
  33.         data = d;
  34.     }    
  35.     /*  Function to get link to next node  */
  36.     public Node getLink()
  37.     {
  38.         return link;
  39.     }    
  40.     /*  Function to get data from current Node  */
  41.     public int getData()
  42.     {
  43.         return data;
  44.     }
  45. }
  46.  
  47. /*  Class linkedStack  */
  48. class linkedStack
  49. {
  50.     protected Node top ;
  51.     protected int size ;
  52.  
  53.     /*  Constructor  */
  54.     public linkedStack()
  55.     {
  56.         top = null;
  57.         size = 0;
  58.     }    
  59.     /*  Function to check if stack is empty */
  60.     public boolean isEmpty()
  61.     {
  62.         return top == null;
  63.     }    
  64.     /*  Function to get the size of the stack */
  65.     public int getSize()
  66.     {
  67.         return size;
  68.     }    
  69.     /*  Function to push an element to the stack */
  70.     public void push(int data)
  71.     {
  72.         Node nptr = new Node (data, null);
  73.         if (top == null)
  74.             top = nptr;
  75.         else
  76.         {
  77.             nptr.setLink(top);
  78.             top = nptr;
  79.         }
  80.         size++ ;
  81.     }    
  82.     /*  Function to pop an element from the stack */
  83.     public int pop()
  84.     {
  85.         if (isEmpty() )
  86.             throw new NoSuchElementException("Underflow Exception") ;
  87.         Node ptr = top;
  88.         top = ptr.getLink();
  89.         size-- ;
  90.         return ptr.getData();
  91.     }    
  92.     /*  Function to check the top element of the stack */
  93.     public int peek()
  94.     {
  95.         if (isEmpty() )
  96.             throw new NoSuchElementException("Underflow Exception") ;
  97.         return top.getData();
  98.     }    
  99.     /*  Function to display the status of the stack */
  100.     public void display()
  101.     {
  102.         System.out.print("\nStack = ");
  103.         if (size == 0) 
  104.         {
  105.             System.out.print("Empty\n");
  106.             return ;
  107.         }
  108.         Node ptr = top;
  109.         while (ptr != null)
  110.         {
  111.             System.out.print(ptr.getData()+" ");
  112.             ptr = ptr.getLink();
  113.         }
  114.         System.out.println();        
  115.     }
  116. }
  117.  
  118. /* Class LinkedStackImplement */
  119. public class LinkedStackImplement
  120. {    
  121.     public static void main(String[] args)
  122.     {
  123.         Scanner scan = new Scanner(System.in);   
  124.         /* Creating object of class linkedStack */   
  125.         linkedStack ls = new linkedStack();          
  126.         /* Perform Stack Operations */  
  127.         System.out.println("Linked Stack Test\n");  
  128.         char ch;     
  129.         do 
  130.         {
  131.             System.out.println("\nLinked Stack Operations");
  132.             System.out.println("1. push");
  133.             System.out.println("2. pop");
  134.             System.out.println("3. peek");
  135.             System.out.println("4. check empty");
  136.             System.out.println("5. size");            
  137.             int choice = scan.nextInt();
  138.             switch (choice) 
  139.             {
  140.             case 1 :
  141.                 System.out.println("Enter integer element to push");
  142.                 ls.push( scan.nextInt() ); 
  143.                 break;                         
  144.             case 2 : 
  145.                 try
  146.                 {
  147.                     System.out.println("Popped Element = "+ ls.pop());
  148.                 }
  149.                 catch (Exception e)
  150.                 {
  151.                     System.out.println("Error : " + e.getMessage());
  152.                 }    
  153.                 break;                         
  154.             case 3 : 
  155.                 try
  156.                 {
  157.                     System.out.println("Peek Element = "+ ls.peek());
  158.                 }
  159.                 catch (Exception e)
  160.                 {
  161.                     System.out.println("Error : " + e.getMessage());
  162.                 }
  163.                 break;                         
  164.             case 4 : 
  165.                 System.out.println("Empty status = "+ ls.isEmpty());
  166.                 break;                
  167.             case 5 : 
  168.                 System.out.println("Size = "+ ls.getSize()); 
  169.                 break;                
  170.             case 6 : 
  171.                 System.out.println("Stack = "); 
  172.                 ls.display();
  173.                 break;                        
  174.             default : 
  175.                 System.out.println("Wrong Entry \n ");
  176.                 break;
  177.             }           
  178.             /* display stack */    
  179.             ls.display();            
  180.             System.out.println("\nDo you want to continue (Type y or n) \n");
  181.             ch = scan.next().charAt(0);       
  182.  
  183.         } while (ch == 'Y'|| ch == 'y');                 
  184.     }
  185. }

Linked Stack Test
 
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
5
 
Stack = 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
33
 
Stack = 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
24
 
Stack = 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
87
 
Stack = 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
99
 
Stack = 99 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
1
 
Stack = 1 99 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
5
Size = 6
 
Stack = 1 99 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
3
Peek Element = 1
 
Stack = 1 99 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 1
 
Stack = 99 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 99
 
Stack = 87 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 87
 
Stack = 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
5
Size = 3
 
Stack = 24 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 24
 
Stack = 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
3
Peek Element = 33
 
Stack = 33 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 33
 
Stack = 5
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 5
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
2
Error : Underflow Exception
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
3
Error : Underflow Exception
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
y
 
Linked Stack Operations
1. push
2. pop
3. peek
4. check empty
5. size
4
Empty status = true
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.