codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
/* 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(int 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 *append(List *xs, List *ys) { List *new = xs; while (xs->next != NULL) { xs = xs->next; } xs->next = ys; return new; } 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)); ys = NULL; ys = insert(5, ys); ys = insert(4, ys); xs = append(xs, ys); xs = reverse(xs); ys = xs; while (ys != NULL) { printf("%d\n", ys->data); ys = ys->next; } return 0; }
Private
[
?
]
Run code
Submit