Skip to content

Instantly share code, notes, and snippets.

@tscho
Created January 12, 2012 21:47
Show Gist options
  • Save tscho/1603353 to your computer and use it in GitHub Desktop.
Save tscho/1603353 to your computer and use it in GitHub Desktop.
It's a linked list. Of numbers. Yay. At least it can reverse itself in O(N) time.
#include <stdio.h>
#include <stdlib.h>
#define null 0
typedef struct _node {
int value;
struct _node *next;
} node;
node *push (node *head, node *new);
node *pop (node *head);
node *reverse (node *head);
void printl(node *head);
int main(int argc, char *argv[]) {
int i;
node *head, *new;
if(argc > 1) {
i = atoi(argv[1]);
} else {
i = 6;
}
head = null;
for(; i > 0; i--) {
new = malloc(sizeof(node));
new->value = i;
head = push(head, new);
}
printf("Before:\n");
printl(head);
printf("\nAfter:\n");
head = reverse(head);
printl(head);
}
node *push (node *head, node *new) {
new->next = head;
return new;
}
node *pop (node *head) {
node *curr = head;
head = curr->next;
return curr;
}
node *reverse (node *head) {
node *prev, *curr, *next;
unsigned int iterations = 0;
curr = head;
prev = null;
while(curr) {
iterations++;
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
printf("Reversed list in %u iterations\n", iterations);
return prev;
}
void printl(node *head) {
for(;head;head = head->next) {
printf(" %-2d (0x%08X)\n", head->value, (unsigned int)head);
if(head->next)
printf(" | \n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment