码迷,mamicode.com
首页 > 其他好文 > 详细

链表逆置

时间:2014-10-14 16:52:28      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   ar   for   sp   div   

 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,布布扣

链表逆置

标签:style   blog   http   color   os   ar   for   sp   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!