Skip to content

Instantly share code, notes, and snippets.

@jgrar
Last active August 29, 2015 14:01
Show Gist options
  • Save jgrar/1112f6f290e9d854de59 to your computer and use it in GitHub Desktop.
Save jgrar/1112f6f290e9d854de59 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
struct list {
int v;
struct list *next;
};
void reverse (struct list **head) {
struct list *p, *n;
if (*head == NULL) {
return;
}
p = (*head)->next;
(*head)->next = NULL;
while (p != NULL) {
n = p->next;
p->next = *head;
*head = p;
p = n;
}
}
void dump (struct list *l) {
for (; l != NULL; l = l->next) {
printf(" %p -> %d, %p\n", l, l->v, l->next);
}
fputc('\n', stdout);
}
void push (struct list **l, struct list *new) {
new->next = *l;
*l = new;
}
void unshift (struct list **l, struct list *new) {
reverse(l);
push(l, new);
reverse(l);
}
void destroy (struct list *l) {
struct list *p;
while (l != NULL) {
p = l->next;
free(l);
l = p;
}
}
int main () {
struct list *l, *p;
int i;
l = NULL;
for (i = 0; i < 10; i++) {
p = malloc(sizeof(*p));
if (p == NULL) {
exit(EXIT_FAILURE);
}
p->v = i;
p->next = NULL;
push(&l, p);
}
dump(l);
reverse(&l);
dump(l);
destroy(l);
l = NULL;
for (i = 0; i < 10; i++) {
p = malloc(sizeof(*p));
if (p == NULL) {
exit(EXIT_FAILURE);
}
p->v = i;
p->next = NULL;
unshift(&l, p);
}
dump(l);
destroy(l);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment