------------------------------------------------------------------------------
MC logo
C++ Integer Stack ADT
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Point Hdr File] [Point Impl File] [Point User File] [Point Class Hdr File] [Point Class Impl File] [Point Class User File] [C++ Integer Stack ADT] [C++ Integer Stack Implementation] [C++ Integer Stack Driver]
istack2.h
#include <iostream>

#ifndef _ISTACK2_H_
#define _ISTACK2_H_

using namespace std;

// Stack of integers.  This is the class definition.
class IntStack {
        // Node structure.
        struct node {
                int val;        // Data in this node.
                node *next;     // Next node.

                // Construct a newly-created node.
                node(int v, node *n) { val = v; next = n; }

                // Delete all the nodes.
                void killall() { 
                        if(next) next->killall();
                        delete this;
                }

                // Print all the nodes.
                void printall(ostream &strm) { 
                        strm << val << " ";
                        if(next) next->printall(strm);
                }
        } *head;

 public:
        // Nice new empty.
        IntStack() { head = NULL; }

        // Make it go away.
        ~IntStack() { if(head != NULL) head->killall(); }

        // Operations.
        bool empty() const { return head == NULL; }
        void push(int i) { head = new node(i, head); }
        int pop();
        int top() const { return head->val; }

        // Print contents
        void print(ostream &) const;
};

// Overload << to allow printing of stacks with other objects.
inline ostream & operator<<(ostream &strm, const IntStack &s)
{
        s.print(strm);
        return strm;
}

#endif