In: Computer Science
Program in Java
Create a stack class to store integers and implement following methods:
1- void push(int num): This method will push an integer to the top of the stack.
2- int pop(): This method will return the value stored in the top of the stack. If the stack is empty this method will return -1.
3- void display(): This method will display all numbers in the stack from top to bottom (First item displayed will be the top value).
4- Boolean isEmpty(): This method will check the stack and if it is empty, this will return true, otherwise false.
class Stack {
final int MAX = 100;
private int top;
private int a[] = new int[MAX]; // Maximum size of Stack
private int min;
// constructer calls when the object is created
Stack() {
top = -1; // initialize top value -1
}
// this method is used to insert values into stack
public void push(int x) {
if (top >= (MAX - 1)) // here we check the condition if values are there are not
{
System.out.println("Stack Overflow");
} else {
a[++top] = x;
}
}
// this method is used to delete top element
public int pop() {
if (top < 0) // here also we check the condition if values are there are not
{
return -1;
} else {
int x = a[top--];
return x;
}
}
public boolean isEmpty() {
return top < 0;
}
public void display() {
for(int i=top-1;i>=0;i--)
System.out.print(a[i]+" ");
System.out.println();
}
}
public class TestIntegerStack {
public static void main(String[] args) {
Stack s = new Stack();
System.out.println(s.isEmpty());
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
s.push(60);
s.display();
s.pop();
s.display();
System.out.println(s.isEmpty());
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
Please Like and Support me as it helps me a lot