icse-promo

Question

 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:
Classname: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 top most 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.

(a) Specify class Stack giving details of the constructors( ), void pushname (String n), String popname() and void display().
THE MAIN() FUNCTION AND ALGORITHM NEED NOT BE WRITTEN.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					public class Stack
{
    String st[]=new String[50];
    int size,top,ctr,f;

    public Stack(int cap)	
    {
        size=cap;
        f=0;
        top=-1;
        st=new String[size];
    }
 
    public void pushname(String n)
    {
        if(top< size)
        { 
            top=top+1;
            st[top]=n;
        }
        else
        {
            System.out.println("OVERFLOW");
        }
    } 
    public String popname()
    {
 
        String v;
        if(top>=0)
        {
            top=top-1;
            v=st[top];
            return v;
        }
        else
        {
            System.out.println("UNDERFLOW");
            return " ";
        }

    }
 

    public void display()
    {
        
        for(int i=top;i>=0;i--)
        {
            System.out.println(st[i]);
        }
    }
}


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *