-2

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148

2 Answers2

1

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());
   }

}
JTeam
  • 1,455
  • 1
  • 11
  • 16
-1

Assumming when there is nothing in the stack, s.peek() will return null,

while(s.peek() != null){
    System.out.println(s.pop());
}
Tan Li Hau
  • 1,984
  • 17
  • 24