Array_to_Stack

ISC Computer Science 2014

Question 12.

A stack is a linear data structure which enables the user to add and remove integers from the end only, using the concept of LIFO( Last In First Out). An array containing the marks of 50 students in ascending order is to be pushed into the stack.

Define a class Array_to_Stack with the following details:

Class: Array_to_Stack

Data members/instance variables:

m[] : to store the marks

st[]: to store the stack elements

cap : maximum capacity of the array and stack

top : to point the index of the topmost element of the stack

Method/member functions:

Array_to_Stack(int n): parametrized constructor to initialize cap=n 
                       and top=-1

void input_marks()   : to input the marks from the user and store it 
                       in the array m[] in ascending order and 
                       simultaneously push the marks into the stack st[] 
                       by invoking the function pushmarks()

int popmarks()       : to return marks from the stack if possible, 
                       otherwise, return -999

void display()       : To display the stack elements

Specify the class Array_to_Stack, giving the details of the constructor(int), void input_marks(), void pushmarks(int), int popmarks() and void display().
The main function and the algorithm need not be written.


Implementation of the class Array_to_Stack is as follows:

import java.util.*;
class Array_to_Stack{
    private int m[], st[], cap, top;
    public Array_to_Stack( int n ){
        m = new int[ n ];
        st = new int[ n ];
        cap = n;
        top = -1;
    }
    public void input_marks(){
        Scanner sc = new Scanner( System.in );
        System.out.println("Enter " + m.length + " marks(int): ");
        for( int i = 0; i < m.length; i++ ){
            m[ i ] = sc.nextInt();
        }
    }
    public void pushmarks( int v ){
        if( top == st.length - 1 ){
            System.out.println("not possible");
        }else{
            st[ ++top ] = v;
        }
    }
    public int popmarks(){
        if( top == -1 ){
            return -999;
        }else{
            return st[ top-- ];
        }
    }
    public void display(){
        System.out.println("Stack elements( top on the left )");
        for( int i = top; top < st.length; i++ ){
            System.out.print( st[ i ] + " ");
        }
        System.out.println();
    }
}

I would like to point out that question is asking to specifically print a message in case of overflow and underflow. This is not a best or recommended practise. Refer to my earlier post Stack in Java for a better way to do the same thing. Also note that there is no need to store the capacity (cap) as an instance variable because the capacity is always available as st.length. I have included it in the solution because the question explicitly asked for it.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.