forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversingLinkedList.c
More file actions
70 lines (62 loc) · 1.34 KB
/
reversingLinkedList.c
File metadata and controls
70 lines (62 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Program to reverse linked list using recursion.
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *link;
} *START = NULL;
void insertNode(int);
void printLinkedList();
void reverseLinkedList(struct Node *);
int main(){
insertNode(10);
insertNode(20);
insertNode(30);
insertNode(40);
printf("Original Linked List: ");
printLinkedList();
reverseLinkedList(START);
printf("Reversed Linked List: ");
printLinkedList();
return 0;
}
void insertNode(int key){
struct Node *ptr = malloc(sizeof(struct Node));
ptr->data = key;
ptr->link = NULL;
if(START == NULL){
START = ptr;
return;
}
struct Node *temp = START;
while(temp->link != NULL){
temp = temp->link;
}
temp->link = ptr;
}
void printLinkedList(){
if(START == NULL){
printf("Empty Linked List!\n");
return;
}
struct Node *ptr = START;
while(ptr != NULL){
printf("%d ", ptr->data);
ptr = ptr->link;
}
printf("\n");
}
// Reversing Linked List using Recursion
void reverseLinkedList(struct Node *ptr){
if(ptr == NULL) {
return;
}
if(ptr->link == NULL){
START = ptr;
return;
}
reverseLinkedList(ptr->link);
struct Node *temp = ptr->link;
temp->link = ptr;
ptr->link = NULL;
}