1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
#include "stack.hpp"
#include <cassert>
#include <iostream>
#include <utility>

void
Stack_construct_default(Stackconst this_)
{
    this_->topnullptr;
}

void
Stack_construct_copy(Stackconst this_, const Stackconst stack)
{
    // start with default constructed stack
    Stack_construct_default(this_);
    // then fill it with a copy
    Stack_copy_elements_(this_, stack->top);
}

void
Stack_construct_swap(Stackconst this_, Stackconst stack)
{
    std::swap(this_->top, stack->top);
}

void
Stack_destruct(Stackconst this_)
{
    while (!Stack_isEmpty(this_)) {
        Stack_pop(this_);
    }
}

bool
Stack_isEmpty(const Stackconst this_)
{
    return !this_->top;
}

Stackconst
Stack_assign(Stackconst this_, Stackconst stack)
{
    std::swap(this_->top, stack->top);
    return this_;
}

void
Stack_push(Stackconst this_, double value)
{
    Stack_Element *add = new Stack_Element;

    add->value   = value;
    add->last    = this_->top;
    this_->top   = add;
}

double
Stack_pop(Stackconst this_)
{
    assert(!Stack_isEmpty(this_));

    Stack_Element *remove = this_->top;
    this_->top            = remove->last;
    double value          = remove->value;
    delete remove;
    return value;
}

void
Stack_print(Stackconst this_, const char *txt)
{
    if (txt) {
        std::cout << txt << std::endl;
    } else {
        std::cout << "Stack contains:" << std::endl;
    }
    Stack_print_elements_(this_, this_->top);
    std::cout << std::endl;
}

void
Stack_copy_elements_(Stackconst this_, const Stack_Element *element)
{
    if (element) {
        Stack_copy_elements_(this_, element->last);
        Stack_push(this_, element->value);
    }
}

void
Stack_print_elements_(const Stackconst this_, const Stack_Element *element)
{
    if (element) {
        Stack_print_elements_(this_, element->last);
        std::cout << element->value << "   ";
    }
}