Stack ADT using Interface
Design a Java interface for ADT Stack. Implement this interface using an array. Provide
necessary exception handling in both the implementations.
The interface Stack must have the following method signatures.
void push(int data)
int pop()
int peek()
boolean isEmpty()
void display()
Note: The display() method must print all the elements of the stack separated by a space in the
order of insertion if the stack is not empty. Else it throws necessary exception.
The query type can be any one of the following types.
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - isEmpty
Example Input/Output 1:
Input:
19
1 10
1 20
1 30
1 40
4
2
4
2
3
4
1 50
4
5
2
2
2
2
3
5
Output:
Stack Elements: 10 20 30 40
Popped Element: 40
Stack Elements: 10 20 30
Popped Element: 30
Top Element: 20
Stack Elements: 10 20
Stack Elements: 10 20 50
FALSE
Popped Element: 50
Popped Element: 20
Popped Element: 10
Stack Underflow
Stack Empty
TRUE
Java
import java.util.*;
interface Stack {
void push(int data);
int pop();
int peek();
void display();
boolean isEmpty();
}
class ArrayStack implements Stack {
public int SIZE;
public int[] stack;
public int top = -1;
public ArrayStack(int SIZE) {
this.SIZE = SIZE;
this.stack = new int[SIZE];
}
@Override
public void push(int data) throws IndexOutOfBoundsException {
if (top + 1 < SIZE) {
stack[++top] = data;
} else {
throw new IndexOutOfBoundsException();
}
}
@Override
public int pop() throws EmptyStackException {
if (!isEmpty()) {
return stack[top--];
} else {
throw new EmptyStackException();
}
}
@Override
public int peek() throws EmptyStackException {
if (!isEmpty()) {
return stack[top];
} else {
throw new EmptyStackException();
}
}
@Override
public boolean isEmpty() {
return top == -1;
}
@Override
public void display() throws EmptyStackException {
if (!isEmpty()) {
for (int index = 0; index <= top; index++) {
System.out.print(stack[index] + " ");
}
} else {
throw new EmptyStackException();
}
}
}
public class Hello {
static final int SIZE = 100;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack stack = new ArrayStack(SIZE);
int N = sc.nextInt();
for (int query = 1; query <= N; query++) {
int queryType = sc.nextInt();
switch (queryType) {
case 1:
try {
stack.push(sc.nextInt());
} catch (Exception e) {
System.out.println("Stack Overflow");
}
break;
case 2:
try {
System.out.println("Popped Element: " + stack.pop());
} catch (Exception e) {
System.out.println("Stack Underflow");
}
break;
case 3:
try {
System.out.println("Top Element: " + stack.peek());
} catch (Exception e) {
System.out.println("Stack Empty");
}
break;
case 4:
try {
System.out.print("Stack Elements: ");
stack.display();
System.out.println();
} catch (Exception e) {
System.out.println("Stack Empty");
}
break;
case 5:
if (stack.isEmpty()) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
}
}