Created
April 25, 2012 07:41
-
-
Save zhpengg/2487842 to your computer and use it in GitHub Desktop.
单链表翻转
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
#include <stdlib.h> | |
#include <stdio.h> | |
struct node { | |
int item; | |
struct node* next; | |
}; | |
typedef struct node node; | |
typedef node * link_list; | |
void list_dump(link_list list) | |
{ | |
while (list) { | |
printf("%d ", list->item); | |
list = list->next; | |
} | |
printf("\n"); | |
} | |
int main() | |
{ | |
link_list list = NULL; | |
int i; | |
for (i = 0; i < 10; i++) { | |
node *n = (node *)malloc(sizeof(node)); | |
if (n) { | |
n->item = i; | |
n->next = list; | |
list = n; | |
} else { | |
perror("molloc"); | |
return -1; | |
} | |
} | |
list_dump(list); | |
// revert | |
if (!list) { | |
return -1; | |
} | |
node *pre = NULL; | |
node *cur = list; | |
node *next = cur->next; | |
while (next) { | |
cur->next = pre; | |
pre = cur; | |
cur = next; | |
next = cur->next; | |
} | |
cur->next = pre; | |
list = cur; | |
list_dump(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment