File tree Expand file tree Collapse file tree 1 file changed +18
-3
lines changed Expand file tree Collapse file tree 1 file changed +18
-3
lines changed Original file line number Diff line number Diff line change 2
2
Recursive program to reverse a linked list
3
3
*/
4
4
5
+ #include <stdio.h>
6
+ #include <stdlib.h>
7
+
5
8
struct node {
6
9
int data ;
7
10
struct node * link ;
8
11
};
9
12
13
+ struct node * head ;
14
+
10
15
void printList (struct node * t ){
11
16
if (t ){
12
17
//interchanging these lines will print it in reverse order
@@ -15,9 +20,18 @@ void printList(struct node *t){
15
20
}
16
21
}
17
22
23
+ void reverse (struct node * prev , struct node * curr ){
24
+ if (curr ){
25
+ reverse (curr , curr -> link );
26
+ curr -> link = prev ;
27
+ }else {
28
+ head = prev ;
29
+ }
30
+ }
31
+
18
32
int main (){
19
33
20
- struct node * head = (struct node * )malloc (sizeof (struct node ));
34
+ head = (struct node * )malloc (sizeof (struct node ));
21
35
22
36
struct node * t = head ;
23
37
@@ -39,6 +53,7 @@ int main(){
39
53
printList (t );
40
54
t = head ;
41
55
42
-
43
-
56
+ reverse (NULL ,head );
57
+ t = head ;
58
+ printList (t );
44
59
}
You can’t perform that action at this time.
0 commit comments