
reverse_linked_list
By: a guest on Aug 14th, 2010 | syntax:
C | size: 1.25 KB | hits: 50 | expires: Never
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *next;
char data;
};
// The last node must have n->next == NULL
struct node *reverse_list(struct node *current, struct node *last) {
struct node *next = current->next;
current->next = last;
if (next != NULL) {
return reverse_list(next, current);
} else {
return current;
}
}
struct node *reverse_list2(struct node *top) {
struct node *next, *last = top, *first = top;
while (top->next != NULL) {
next = top->next;
top->next = last;
last = top;
top = next;
}
top->next = last;
first->next = NULL;
return top;
}
int main(int argc, char **argv) {
char i;
struct node *top, *current;
current = top = malloc(sizeof(struct node));
current->data = 'a';
for (i = 'b'; i <= 'z'; i++) {
current->next = malloc(sizeof(struct node));
current = current->next;
current->data = i;
}
struct node *reversed = reverse_list(top, NULL);
struct node *r = reversed;
// print
while (reversed != NULL) {
printf("%c", reversed->data);
reversed = reversed->next;
}
printf("\n");
reversed = reverse_list2(r);
// print
while (reversed != NULL) {
printf("%c", reversed->data);
reversed = reversed->next;
}
printf("\n");
}