1 //逆转链表http://blog.163.com/lichunliang1988116@126/blog/static/26599443201282083655446/
2 #include<iostream.h>
3 #include<stdlib.h>
4 typedef struct Node
5 {
6 int data;
7 Node *next;
8 }*Linklist,ListNode;
9 void initLink(Linklist *head)
10 {
11
12 Node *node=(Node *)malloc(sizeof(Node));
13 node->data=0;
14 node->next=NULL;
15
16 head=&node;
17
18 }
19
20 void addNode(Linklist head,int no)
21
22 {
23 Node *node=(Node *)malloc(sizeof(Node));
24 node->data=no;
25 node->next=NULL;
26 cout<<"加个数据为"<<no<<endl;
27 node->next=head->next;
28 head->next=node;
29 }
30
31
32 void print(Linklist head)
33 {
34 Linklist current=head;
35 while(current!=NULL)
36 {
37 cout<<current->data<<" ";
38 current=current->next;
39
40
41 }
42 cout<<endl;
43
44 }
45 //recursive fanhui head function
46 Linklist recursive2(Linklist head,Linklist &newHead)
47 {
48 if(head->next==NULL)
49 {
50 newHead=head;
51 return head;
52
53 }
54 Node *p1=head;
55 Node *p2;
56
57 p2=recursive2(p1->next,newHead);
58
59 p2->next=p1;
60 p1->next=NULL;
61
62
63 }
64
65
66
67
68
69
70 Linklist reverse1(Linklist head)
71 {
72 //if linklist is a node or null ,we need not inverse the linklist
73 if(head==NULL||head->next==NULL)
74 {
75 return head;
76 }
77
78 Linklist pre=head;
79 Node *current=head->next;
80 Linklist next1=current->next;
81 //notice that head->next should be null;
82 head->next=NULL;
83
84 while(next1!=NULL)
85 {
86 current->next=pre;
87 pre=current;
88
89 current=next1;
90
91
92 next1=next1->next;
93
94
95 }
96
97 current->next=pre;
98
99 return current;
100
101
102
103
104 }
105
106 void main()
107 {
108 cout<<"你好"<<endl;
109 Linklist h=NULL;
110 h=(Node *)malloc(sizeof(Node));
111 h->data=1;
112 h->next=NULL;
113
114
115 addNode(h,4);
116 addNode(h,5);
117 addNode(h,6);
118 cout<<"反转前"<<endl;
119 print(h);
120 h=reverse1(h);
121 print(h);
122 cout<<"revese again"<<endl;
123 recursive2(h,h);
124 print(h);
125
126
127 }