Created
June 30, 2010 00:39
-
-
Save cslarsen/458048 to your computer and use it in GitHub Desktop.
Reverse singly linked list in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Reverse singly linked list. (C) | |
* | |
* Written in a hurry after reading this HN thread: | |
* http://news.ycombinator.com/item?id=1471988 | |
* | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
struct item { | |
const char* msg; | |
struct item* next; | |
}; | |
struct item* new(const char* msg) | |
{ | |
struct item* p = (struct item*) malloc(sizeof(struct item)); | |
p->next = NULL; | |
p->msg = msg; | |
return p; | |
} | |
struct item* append(struct item *p, struct item *next) | |
{ | |
p->next = next; | |
next->next = NULL; | |
return next; | |
} | |
void traverse(struct item* p, void (*func)(struct item*)) | |
{ | |
while ( p != NULL ) { | |
struct item* next = p->next; | |
func(p); | |
p = next; | |
} | |
} | |
void print_info(struct item* p) | |
{ | |
printf("0x%lx: '%s'\n", (long unsigned int) p, p->msg); | |
} | |
void free_struct(struct item* p) | |
{ | |
free(p); | |
} | |
struct item* reverse(struct item* p) | |
{ | |
struct item *root = p, *prev = NULL, *next; | |
while ( p != NULL ) { | |
next = p->next; | |
p->next = prev; | |
prev = p; | |
p = next; | |
} | |
root->next = NULL; | |
return prev; | |
} | |
int main(int argc, char** argv) | |
{ | |
struct item *p = new("one"); | |
struct item *root = p; | |
p = append(p, new("two")); | |
p = append(p, new("three")); | |
p = append(p, new("four")); | |
p = append(p, new("five")); | |
p = append(p, new("six")); | |
printf("Normal list:\n"); | |
traverse(root, print_info); | |
printf("Reversed list:\n"); | |
root = reverse(root); | |
traverse(root, print_info); | |
// no need for this, strictly speaking: | |
traverse(root, free_struct); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment