In: Computer Science
3.1 Implement the stack ADT using array 3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array using array. The starter code is as follows. The instance variables and most operations are provided. You need to implement the pop operation. Make sure that your program checks whether the stack is empty in the pop operation.
import java . io .*;
import java . util .*;
public class Stack2540Array {
int CAPACITY = 128;
int top ;
String [] stack ;
public Stack2540Array () {
stack = new String [ CAPACITY ];
top = -1;
}
public int size () { return top + 1; }
public boolean isEmpty () { return ( top == -1) ; }
public String top () {
if ( top == -1)
return null ;
return stack [ top ];
}
public void push ( String element ) {
top ++;
stack [ top ] = element ;
}
Logic for popping an element from a stack of array
type:-
Removes an item from the stack. The items are popped in the reversed order in which they are pushed initially. If the stack is empty, then it is said to be an Underflow condition. We would implement this with an if-else statement, where the condition will be checking if the stack is empty i.e., top == -1. Since you have created a function to check the same, isEmpty(), we will use this statement in the condition for if-block
Code for pop() in stack ADT using array:-
String pop()
{
if (isEmpty()) //check
if Stack is empty
{
return "Stack is empty";
}
else //If not empty,
then pop the next element
{
String ele = top(); //Assign top to new string element
top--; //Removing top element from the Stack
return ele; //Return the popped element
}
}
In case, you have any doubt.. Please ask in the comment section.
Additional Information:-
I am also providing you a sample driver code and the output for the same.
Driver code:-
public static void main(String args[])
{
//Declare a new class
object
Stack2540Array s = new
Stack2540Array();
//Push some elements
into the stack
s.push("Hello");
s.push("How");
s.push("Are");
s.push("You");
//pop the top
element
System.out.println(s.pop() + " : Popped from stack");
System.out.println(s.pop() + " : Popped from stack");
System.out.println(s.pop() + " : Popped from stack");
System.out.println(s.pop() + " : Popped from stack");
}
Output:-
Thank you.
Happy Learning.