------------------------------------------------------------------------------
MC logo
Java Int Stack Class
[^] Names and Scope
------------------------------------------------------------------------------
[Ch. 1: Overview and History] [Syntax] [Names and Scope] [Types and Type Systems] [Semantics] [Functions] [Memory Management] [Imperitive Programs and Functional Abstraction] [Modular and Class Abstraction] [Functional Programming] [Logic Programming]
[Java Class Scope] [Ada Int Stack Package] [Ada Int Stack Impl] [Ada Int Stack Driver] [Java Int Stack Class] [Java Int Stack Driver] [C++ Int Stack Class] [C++ Int Stack Impl] [C++ Int Stack Driver]
intstack.java
// Implements a stack of integers.
class IntStack {
    // Stack node type.
    private class StackNode {
        StackNode(int d, StackNode n) {
            data = d;
            next = n;
        }
        public int data;
        public StackNode next;
    }
    
    // Head of the stack
    private StackNode head = null;

    // Push onto the stack.
    public void push(int i) {
        head = new StackNode(i, head);
    }

    // Remove from the stack.
    public int pop() {
        if (head != null) {
            // Get the head and remove it.
            int retval = head.data;
            head = head.next;

            // Return the value.
            return retval;
        } else
            return 0;
    }

    // Find out what's on the top.
    public int top() {
        if(head == null)
            return 0;
        else
            return head.data;
    }

    // So, are we empty yet?
    public boolean isEmpty() {
        return head == null;
    }

    // Remove all memory from the stack.
    public void clear() {
        head = null;
    }
}