In: Computer Science
Without using method size(), write recursive method stackSize(Stack > s1 ) that receives a stack and returns number of elements in the stack. The elements in the stack should not be changed after calling this method. please do it in java
Java Program:
import java.util.*;
public class Main {
static int stackSize(Stack stack)
{
if(stack.isEmpty())
{
return 0;
}
stack.pop();
return 1+stackSize(stack);
}
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack = new Stack<Integer>();
// Use add() method to add elements into the Stack
stack.add(10);
stack.add(15);
stack.add(30);
stack.add(20);
int range=stackSize(stack);
System.out.println("Size of Stack is:" +range);
}
}
Output:
Thank you Have a great day!!! Please do like...