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 <string>
using namespace std;

template <class T>
struct Node
{
    T cargo;
    Node<T>* next;

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

    string to_string() const
    {
        return string(cargo);
    }
};


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

    LinkedList() {
        num_nodes = 0;
        head = nullptr;
    }

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

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

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

    int length() const
    {
        return num_nodes;
    }
};

Stack.h

#ifndef STACK_H
#define STACK_H
#define MAX_SIZE 128
#include <stdexcept>

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

public:
    Stack() {
        top_item = -1;
    }

    void push(const T& value) {
        if (top_item >= MAX_SIZE - 1) {
            throw std::overflow_error("Stack overflow");
        }
        items[++top_item] = value;
    }

    T pop() {
        if (empty()) {
            throw std::underflow_error("Stack underflow");
        }
        return items[top_item--];
    }

    const T& top() const {
        if (empty()) {
            throw std::underflow_error("Stack is empty");
        }
        return items[top_item];
    }

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

    size_t size() const {
        return top_item + 1;
    }
};

#endif // STACK_H