Question: Modify your stack implementation in such a way that a client application using your stack is unaware of the underlying array-based implementation. For instance, in

Modify your stack implementation in such a way that a client application using your stack is unaware of the underlying array-based implementation. For instance, in a C or C++ implementation, you would define function prototypes in .h files and implementation details in .c files. In Java and C#, you use interfaces. The application uses the interfaces (or .h files) with no knowledge of how the functions are implemented. That way the array-based implementation could be replaced with a linked list-based one without any change to the client application.

Code

//Stack implementation using array

public class Stack {

// define the max size of stack

private final int SIZE = 5;

// declare other variables

private int top;

private int arr[];

// constructor

public Stack() {

top = -1;

arr = new int[SIZE];

}

// implement various stack methods

public void push(int val) {

// check of stack is full or not

if (top == SIZE) {

System.out.println("Stack is full");

} else {

top++;

arr[top] = val;

}

}

public int pop() {

// check of stack is empty or not

if (top == -1) {

System.out.println("Stack is empty");

return -1;

} else {

top--;

return arr[top + 1];

}

}

public int top() {

// check of stack is empty or not

if (top == -1) {

System.out.println("Stack is empty");

return -1;

} else {

return arr[top];

}

}

public int size() {

return top + 1;

}

public boolean isEmpty() {

// check of stack is empty or not

if (top == -1) {

return true;

} else {

return false;

}

}

public boolean isFull() {

// check of stack is full or not

if (top == SIZE) {

return true;

} else {

return false;

}

}

// main driver code of the program. contains test code

public static void main(String args[]) {

// create Stack

Stack s = new Stack();

// push some values

s.push(10);

s.push(20);

System.out.println("Stack size : " + s.size());

System.out.println("Stack top elem : " + s.top());

System.out.println("Stack is empty ? : " + s.isEmpty());

s.pop();

System.out.println("Stack top elem : " + s.top());

s.pop();

System.out.println("Stack size : " + s.size());

System.out.println("Stack is empty ? : " + s.isEmpty());

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!