首页 > 代码库 > 链表逆置

链表逆置

 1 #include "stdafx.h" 2 struct node  3 { 4     int data; 5     node * next; 6 }; 7  8 node * create_list(int a[], int n) 9 {10     if (n <= 0)11         return NULL;12     node * first = new node;13     first->data = http://www.mamicode.com/a[0];14     first->next = NULL;15     node *cur = first;16     for (int i=1;i<n;i++)17     {18         node * next = new node;19         next->data =http://www.mamicode.com/ a[i];20         next->next = NULL;21         cur->next = next;22         cur = next;23     }24     return first;25 }26 27 void printf_list(node *head)28 {29     while(head)30     {31         printf("%d ", head->data);32         head = head->next;33     }34 }35 36 node * reserve_list(node *head)37 {38     node *pre = head, *post = head->next;39     while(post)40     {41         node * temp = post->next;42         post->next = pre;43         if (pre == head)44             pre->next = NULL;45         pre = post;46         post = temp;47     }48     return pre;49 }50 51 int _tmain(int argc, _TCHAR* argv[])52 {53     int a[] = {1,2,3,4,5,6,7,8,9};54     node * head = create_list(a, sizeof(a)/sizeof(int));55     printf_list(head);56     printf("\n");57     node *reservedHead = reserve_list(head);58     printf_list(reservedHead);59     getchar();60     return 0;61 }

链表逆置