[ create a new paste ] login | about

Link: http://codepad.org/m8492b48    [ raw code | output | fork ]

programmingpraxis - C, pasted on Oct 10:
/* imperative-style linked lists */

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

void error(char *str) {
    fprintf(stderr, "error: %s\n", str);
    exit(2);
}

typedef struct list {
    void *data;
    struct list *next;
} List;

List *insert(void *data, List *next) {
    List *new;

    new = malloc(sizeof(List));
    new->data = data;
    new->next = next;
    return new;
}

int nth(List *xs, int n) {
    while (n > 0) {
        if (xs == NULL) {
            error("nth out of bounds");
        }
        n--;
        xs = xs->next;
    }
    return xs->data;
}

int length(List *xs) {
    int len = 0;
    while (xs != NULL)
    {
        len += 1;
        xs = xs->next;
    }
    return len;
}

List *reverse(List *list) {
    List *new = NULL;
    List *next;

    while (list != NULL)
    {
        next = list->next;
        list->next = new;
        new = list;
        list = next;
    }

    return new;
}

int main(int argc, char **argv) {
    List *xs = NULL;
    List *ys = NULL;

    xs = insert(3, xs);
    xs = insert(2, xs);
    xs = insert(1, xs);

    ys = xs;
    while (ys != NULL) {
        printf("%d\n", ys->data);
        ys = ys->next;
    }

    printf("%d\n", nth(xs, 0));
    printf("%d\n", length(xs));

    xs = reverse(xs);

    ys = xs;
    while (ys != NULL) {
        printf("%d\n", ys->data);
        ys = ys->next;
    }

    return 0;
}


Output:
1
2
3
4
5
6
7
8
1
2
3
1
3
3
2
1


Create a new paste based on this one


Comments: