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

struct lst2 {
    int x;
    struct lst2 *n, *p;
};

struct dq {
    struct lst2 *f, *l;
};

struct dq *dqini() {
    struct dq *d;
    d = malloc(sizeof(*d));
    d->f = NULL;
    d->l = NULL;
    return d;
}

int dqemp(struct dq *d) {
    if (d->f)
        return 0;
    else
        return 1;
}

void dqpsf(struct dq *d, int x) {
    struct lst2 *t;
    t = malloc(sizeof(*t));

    t->x = x;
    t->p = NULL;
    t->n = d->f;

    if (d->f) {
        d->f->p = t;
    } else {
        d->l = t;
    }
    d->f = t;
}

void dqpsb(struct dq *d, int x) {
    struct lst2 *t;
    t = malloc(sizeof(*t));

    t->x = x;
    t->n = NULL;
    t->p = d->l;

    if (d->l) {
        d->l->n = t;
    } else {
        d->f = t;
    }
    d->l = t;
}

void dqppf(struct dq *d, int *x) {
    struct lst2 *t;

    t = d->f;
    *x = t->x;

    d->f = d->f->n;
    if (d->f)
        d->f->p = NULL;
    else
        d->l = NULL;

    free(t);
}

void dqppb(struct dq *d, int *x) {
    struct lst2 *t;

    t = d->l;
    *x = t->x;

    d->l = d->l->p;
    if (d->l)
        d->l->n = NULL;
    else
        d->f = NULL;

    free(t);
}

int main() {
    int x;
    int a[] = {1, 2, 3, 4};
    int n = sizeof(a)/sizeof(*a);
    struct dq *d;

    d = dqini();

    for (int i = 0; i < n; i++) {
        dqpsb(d, a[i]);
    }

    for (int i = 0; i < n; i++) {
        if (!dqemp(d)) {
            dqppf(d, &x);
            printf("%d ", x);
        }
    }
    printf("\n");

    return 0;
}
