summaryrefslogtreecommitdiffstats
path: root/2022-2/L6/mitsuo/BibliotecaPilaGenerica.cpp
blob: 01a7dc3e224b46dcfbf424b856367173ce4010f7 (plain)
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
99
#include <iostream>
#include <fstream>
#include "BibliotecaPilaGenerica.h"

using namespace std;

/* NEXT: (void *), DATA: (int *) */
enum nodeIndices { NEXT, DATA };

void cargapila(void *&pila, void *arreglo)
{
    int i;
    int **numbers = (int **) arreglo;
    pila = nullptr;
    for (i = 0; numbers[i]; i++) {
        push(pila, numbers[i]);
    }
}

void push(void *&pila, void *data)
{
    void **node = new void * [2];
    node[NEXT] = pila;
    node[DATA] = data;
    pila = node;
}

void *pop(void *&pila)
{
    void **node;
    if (pila == nullptr) {
        return nullptr;
    } else {
        node = (void **) pila;
        pila = node[NEXT];
        return node[DATA];
    }
}

int pilavacia(void *pila)
{
    return pila == nullptr;
}

void imprimepila(
        void *pila, 
        void (*imprimenumero)(ostream &out, void *), 
        const char *filename
) {
    ofstream out(filename);
    if (!out) {
        cerr << "Error: no se pudo abrir archivo\n";
    }
    void **next;
    void **node;
    int data;

    next = (void **) pila;
    while (next) {
        node = (void **) next;
        imprimenumero(out, node[DATA]);

        next = (void **) node[NEXT];
    }
}

/* hanoi */
void muevepila(void *pilasrc, void *&piladest)
{
    void *pilaaux = nullptr;

    /* count elements */
    int i = 0;
    void **next = (void **) pilasrc;
    while (next) {
        next = (void **) *next;
        i++;
    }
    // cout << "n = " << i << '\n';
    hanoi(i, pilasrc, nullptr, piladest);
}

static void hanoi(int n, void *pila1, void *pila2, void *pila3)
{
    /* FIXME: I don't know where it's the bug.  Here or in pop().  Also the stack
     * representation different from what is asked in the problem statement */
    void *data;
    if (n == 0) {
        return;
    } else if (n == 1) {
        data = pop(pila1);
        push(pila3, data);
    } else {
        hanoi(n - 1, pila1, pila3, pila2);
        data = pop(pila1);
        push(pila3, data);
        hanoi(n - 1, pila2, pila1, pila3);
    }
}