/* * Simple C++ list of integers. Everything is in one file for * simplicity of presentation. */ #include #include class IntegerList; /* * Each element of the integer list (IntegerList::Element) consists of * a value and a pointer to the next element. The head of the list is * represented by the IntegerList class itself, which is the only * thing visible from the outside. */ class IntegerList { public: IntegerList(); ~IntegerList(); void push(int newValue); // Add a value to list int pop(); // Take a value off list private: /* * Auxiliary subclass that holds the actual data */ class Element { friend IntegerList; // List class does all work private: Element(int value_ = 0, Element* next_ = NULL); ~Element(); Element* next; // Next element in list int value; // Value stored }; /* * Private data */ Element* head; // First element in the list }; int main( // Test IntegerList int argc, // Argument count char* argv[]) // Arguments { IntegerList values; for (int i = 1; i < argc; i++) values.push(atoi(argv[i])); for (int i = 1; i < argc; i++) cout << values.pop() << endl; return 0; } IntegerList::IntegerList() : head(NULL) { } IntegerList::~IntegerList() { /* * Delete all of the elements stored in the list */ while (head != NULL) { Element* nextElement = head->next; delete head; head = nextElement; } } void IntegerList::push( // Push onto head of list int newValue) // Value to push { Element* newCell = new Element; newCell->value = newValue; newCell->next = head; head = newCell; } int IntegerList::pop() // Return & remove list head { int result = head->value; // Segfaults if empty! Element* disappearingCell = head; // Save for deletion head = head->next; // Remove list head delete disappearingCell; // ..and return the memory return result; } IntegerList::Element::Element( int value_, // Value to store in list Element* next_) // Next Element on list : next(next_), value(value_) { } IntegerList::Element::~Element() { }