Search code examples
javastackpeek

How to remove and print every item in an IntStack object until it is empty?


I am having trouble figuring out how to remove and print every item in an IntStack object until it is empty. Would I need to use an if statement? I know the basics of stacks, for example: Suppose s refers to an IntStack object.

If I wanted to add the value 100 to the top of s, I would simply use s.push(100)

If I wanted to remove and print the top value of s, I would use s.pop()

If I wanted to print the top value without removing it, I would use s.peek()

I run into trouble once I try to remove and print every item in s until it is empty.


Solution

  • Even If InStack is some third party stack, as per the description in question it implements all the standard stack methods, so following should work.

    public void print(Stack s)
    {
       while(!s.isEmpty())
       {
           System.out.println(s.pop());
       }
    
    }