APCS Java Subset

ap
Interface Stack

All Known Implementing Classes:
ArrayStack

public interface Stack

The interface for stacks as they will be used on the Advanced Placement Computer Science exam. Exam questions may use the Stack interface as the type for parameters, variables, and fields. Consider the question below which asks for a function that destructively counts and returns the number of items in a stack and the code for the answer. The question can be answered using just the Stack interface.

Write the function stackSize that returns the number of items in parameter s. Note that s is empty after stackSize executes.

 // Returns the number of items in s; s is empty after the function executes.

 public static int stackSize(Stack s)
 {
     int size = 0;
     while (! s.isEmpty()) {
         size++;
         s.pop();
     }
     return size;
 }
 

Note: there is no method size to return the number of elements stored in a stack, the AP subset/interface doesn't include such a method.


Method Summary
 boolean isEmpty()
          Returns true if this stack is empty, otherwise returns false.
 java.lang.Object peekTop()
          Returns the top element of the stack without popping it.
 java.lang.Object pop()
          Pops and returns the top element of the stack.
 void push(java.lang.Object x)
          Push an element onto the top of this stack.
 

Method Detail

isEmpty

public boolean isEmpty()
Returns true if this stack is empty, otherwise returns false.

Returns:
true if this stack is empty, otherwise return false.

push

public void push(java.lang.Object x)
Push an element onto the top of this stack.

Parameters:
x - is the object pushed onto this stack.

pop

public java.lang.Object pop()
Pops and returns the top element of the stack.

Returns:
the just-popped element of the stack
Throws:
java.lang.RuntimeException - if this stack is empty (unchecked)
See Also:
peekTop()

peekTop

public java.lang.Object peekTop()
Returns the top element of the stack without popping it.

Returns:
the top element of the stack
Throws:
java.lang.RuntimeException - if this stack is empty (unchecked)
See Also:
pop()

unofficial documentation for the APCS Java Subset