Stack Program ISC 2011 Theory

Stack is a kind of data structure which can store elements with the restriction that an element can be added or removed from the top only.

The details of the class Stack is given below:
Class name: Stack
Data members/instance variables:
st[]: the array to hold the names.
size: the maximum capacity of the string array.
top: the index of the topmost element of the stack.
ctr: to count the number of elements of the stack.
Member functions:
Stack(): default constructor.
Stack(int cap): constructor to initialize size = cap and top = -1.
void pushName(String n): to push a name into the stack. If the stack is full, display the message “OVERFLOW”.
String popName(): removes a name from the top of the stack and returns it. If the stack is empty, display the message “UNDERFLOW”.
void display(): display the elements of the stack.

Specify the class Stack giving details of the constructors, void pushName(String n), String popName() and void display().

The main() function and the algorithm need not be written.

Under what principle does the above entity work?

import java.io.*;
class Stack{
    String st[];
    int size;
    int top;
    int ctr;
    public Stack(){
        st = new String[5];
        size = 5;
        top = -1;
        ctr = 0;
    }
    public Stack(int cap){
        size = cap;
        st = new String[size];
        ctr = 0;
        top = -1;
    }
    public void pushName(String n){
        if(ctr == size)
            System.out.println("OVERFLOW");
        else{
            st[++top] = n;
            ctr++;
        }
    }
    public String popName(){
        if(top == -1){
            System.out.println("UNDERFLOW");
            return "";
        }
        else{
            ctr--;
            return st[top--];
        }
    }
    public void display(){
        if(top == -1)
            System.out.println("OVERFLOW");
        else{
            for(int i = 0; i <= top; i++)
                System.out.print(st[i] + "\t");
            System.out.println();
        }
    }
}