#include <stdio.h>
#include <stdlib.h>

enum purpose { TEMP, LARGEST, REST };

struct task {
    int from, to, how_many;
    enum purpose why;
    struct task *next;
};

void add_task(struct task **t, int from, int to, int how_many,
        enum purpose why) {
    struct task *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->from = from;
    tmp->to = to;
    tmp->how_many = how_many;
    tmp->why = why;
    tmp->next = *t;
    *t = tmp;
}

void remove_task(struct task **t) {
    struct task *tmp;
    tmp = *t;
    *t = (*t)->next;
    free(tmp);
}

int via_which(int from, int to) {
    if (from != 1 && to != 1)
        return 1;
    else if (from != 2 && to != 2)
        return 2;
    else
        return 3;
}

void case_temp(struct task **t) {
    (*t)->why = LARGEST;
    int how_many = (*t)->how_many;
    if (how_many > 1) {
        int from = (*t)->from;
        int to = via_which((*t)->from, (*t)->to);
        how_many--;
        add_task(t, from, to, how_many, TEMP);
    }
}

void case_largest(struct task **t, int *i) {
    (*t)->why = REST;
    printf("%d\t%d: %d -> %d\n", *i, (*t)->how_many, (*t)->from, (*t)->to);
    (*i)++;
    int how_many = (*t)->how_many;
    if (how_many > 1) {
        int from = via_which((*t)->from, (*t)->to);
        int to = (*t)->to;
        how_many--;
        add_task(t, from, to, how_many, TEMP);
    }
}

void solve(struct task **t, int how_many, int from, int via, int to) {
    add_task(t, from, to, how_many, TEMP);
    for (int i = 1; *t;) {
        switch ((*t)->why) {
            case TEMP:
                case_temp(t);
                break;
            case LARGEST:
                case_largest(t, &i);
                break;
            case REST:
                remove_task(t);
        }
    }
}

int main(int argc, char **argv) {
    int how_many, from = 1, via = 2, to = 3;
    struct task *t = NULL;

    if (argc < 2) {
        fprintf(stderr, "Usage: ./prog <number of disks>\n");
        return 1;
    }
    how_many = atoi(argv[1]);
    if (how_many < 1) {
        fprintf(stderr, "Enter a valid number of disks\n");
        return 2;
    }

    solve(&t, how_many, from, via, to);
    return 0;
}
