Stack implementation using array

   
Introduction:
   Stack is a linear data structure which follows LIFO( Last In First Out ) order.
 
To represent stack consider books are placed in table for the teacher to correct. The note which is submitted last will be corrected first. The person who submits last is quite unlucky isn't it :P

Operations:
push: Inserts element at the top of the stack
pop: Removes element from the top of the stack

Stack implementation using array:

Code:


import java.util.*;
import java.lang.*;
import java.io.*;

class Stack
{
    int SIZE = 10;
    int arr[] = new int[SIZE];
    int top = -1;
    
    public int pop(){
        if (top == -1){
            System.out.println("stack is empty");
            return 0;
        }
        int topelement = arr[top];
        top--;
        return topelement;
    }
    
    public void push(int element){
        if(top == SIZE-1){
            System.out.println("Stack limit reached");
            return;
        }
        arr[++top] = element;
        return;
    }
    
    public static void main (String[] args){
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
System.out.println(s.pop()+ " is popped from the stack");
s.push(4);
System.out.println(s.pop()+ " is popped from the stack");
}
}

Explanation of code:
      Array is created with capacity of size variable. top is initialized to -1, since array index starts from zero. In pop operation we are checking whether the stack is empty by checking if top = -1. Because if there is no element in the stack we cannot perform pop operation. Then we are storing the top most element and decrement top by 1. In push operation we increment top and insert that element that is we are creating the space for the element before insertion.

Illustration: 








Comments

Popular posts from this blog

Tree traversals - Inorder Traversal

Binary Search tree (Insertion)