Appendix A: Code Source

Source code for the LinkedList, Stack, and other examples from the latter part of the book is included here for your convenience.

LinkedList.h

#include <iostream>
#include <string>
using namespace std;

template <class T>
class Node
{
  public:
    T cargo;
    Node<T>* next;

    Node(T cargo, Node<T>* next) {
        this->cargo = cargo;
        this->next = next;
    }
};

template <class T>
class LinkedList
{
  public:
    int num_nodes;
    Node<T>* head;

    // constructors
    LinkedList() {
        num_nodes = 0;
        head = NULL;
    }

    LinkedList(T cargo) {
        num_nodes = 1;
        head = new Node<T>(cargo, NULL);
    }

    // member functions
    int length() const {
        return num_nodes;
    }

    string to_str() const {
        string s = "(";
        Node<T>* node = head;
        while (node != NULL) {
            s += to_string(node->cargo);
            node = node->next;
            if (node != NULL) s += ", ";
        }
        return s + ")";
    }

    // modifiers
    void insert_at_front(T cargo) {
        Node<T>* front = new Node<T>(cargo, head);
        head = front;
        num_nodes++;
    }

    T remove_from_front() {
        if (head == NULL) throw runtime_error("Can't remove from empty list!");
        T cargo = head->cargo;
        Node<T>* front = head;
        head = head->next;
        delete front;
        num_nodes--;
        return cargo;
    }
};

Stack.h

#include <iostream>
#define MAX_SIZE 128
using namespace std;

template <class T>
class Stack
{
    int top_item;
    T items[MAX_SIZE];

  public:
    // constructors
    Stack() { 
        top_item = -1;
    }
    
    // modifiers
    void push(T item) {
        items[top_item++] = item;
    }

    T pop() {
        if (top_item == -1)
           throw runtime_error("Can't pop from empty stack!");
        return items[top_item--];
    }

    bool empty() const {
        return top_item == -1;
    }

    T top() {
       if (top_item == -1)
           throw runtime_error("Can't return top item of empty stack!");
       return items[top_item];
    }
};