Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Stack's Pop method with Recursion

I am self-studying java. I have been studying data structures for the past couple of days. I am reading the book "Data Structures and Algorithms in Java". there is an exercise that I have problem with. it asks for implementing the pop method with recursion so that when the method is called it should delete all the items at once. can anyone help on this? a pointer on how to do it would be much appreciated. thanks. (following is the pop method currently implemented).

    public double pop() // take item from top of stack
{


        return stackArray[top--]; // access item, decrement top
}
like image 785
aaa Avatar asked Sep 16 '26 10:09

aaa


1 Answers

First IMO you should understand how to implement a non-recursive counterpart of this method.

It can be something like this:

public void popAll() {

  while(!stack.isEmpty()) {
      stack.pop();
  }
}

Once you understand this, the recursive version should be easy:

public void popAllRecursive() {

     if(stack.isEmpty()) {
        //nothing to remove, return
        return;
     }
     stack.pop();  // remove one stack element

     popAllRecursive(); // recursive invocation of your method

}

Since its an exercise I just provide you an idea and leave the implementation to you (you can consider to provide the method in class Stack and use the top counter and stackArray - an implementation of your stack.

Hope this helps

like image 73
Mark Bramnik Avatar answered Sep 18 '26 22:09

Mark Bramnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!