Thursday, 7 December 2017

Chapter 2: Data Structure - Stack

Chapter 2: Stack Data Structure

What is stack? Explain.

Stack is a LIFO (Last In First Out) data structure. Push() function is used to add new elements into the Stack Pop() function is used to delete an element from the stack. Adding and deleting of element is allowed at the only one end of the stack called TOP.

Fig DS 1.1 - Stack Data Structure

Stack Overflow:

Stack is said to be in Overflow state when it is completely full.

Stack Underflow:

Stack is said to be in Underflow state if it is completely empty.

Stack Data Structure uses:

  • Reversing of the word.
  • Conversion of expression(Infix to Postfix, Postfix to Prefix) Etc..

Implementation of stack using Array in Java Programming.

To implement the array we need to write the functions for push() and pop() operations.

Steps for PUSH operation

  1. Check if the stack is full or not.
  2. If the stack is full, then print error of overflow and exit the program.
  3. If the stack is not full, then increment the top and add the element.

Steps for POP operation

  1. Check if the stack is empty or not.
  2. If the stack is empty, then print error of underflow and exit the program.
  3. If the stack is not empty, then print the element at the top and decrement the top.

Display Elements in Stack

Steps to Display

  1. Check if the stack is empty or not.
  2. If the stack is empty, then print message stack is empty.
  3. If the stack is not empty, display the elements by looping through the stack.

Java Program to Implement Stack using array


import java.util.Arrays;

public class StackMethods {
    private int top;
    int size;
    int[] stack ;

    public StackMethods(int arraySize){
        size=arraySize;
        stack= new int[size];
        top=-1;
    }

    public void push(int value){
        if(top==size-1){
            System.out.println("Stack is full, can't push a value");
        }
        else{

            top=top+1;
            stack[top]=value;
        }
    }

    public void pop(){
        if(!isEmpty())
            top=top-1;
        else{
            System.out.println("Can't pop...stack is empty");
        }
    }

    public boolean isEmpty(){
        return top==-1;
    }

    public void display(){

        for(int i=0;i<=top;i++){
            System.out.print(stack[i]+ " ");
        }
        System.out.println();
    }
}