链表逆置

时间:2014-10-14 15:10:19   收藏:0   阅读:285
 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 = 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 = 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 }

bubuko.com,布布扣

原文:http://www.cnblogs.com/kira2will/p/4024387.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!