forked from shubhidua/Hacktoberfest-20
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseLinkedList.c
96 lines (86 loc) · 1.93 KB
/
ReverseLinkedList.c
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<stdio.h>
#include<stdlib.h>
struct List {
int data;
struct List *next;
};
void ListPrint(struct List **head) {
struct List *current = *head;
while (current != NULL){
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n\n");
}
void ListInsert(struct List **head, int data) {
struct List *p, *node;
p = *head;
node = (struct List *)malloc(sizeof(struct List));
node->data = data;
node->next = NULL;
if (*head == NULL) {
*head = node;
} else {
while (p->next != NULL){
p = p->next;
}
p->next = node;
}
}
void ReverseIterative(struct List **head) {
struct List *prev, *current, *next;
current = *head;
prev = NULL;
next = NULL;
while(current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
void ReverseRecursion(struct List **head, struct List *p) {
if(p-> next == NULL) {
*head = p;
return;
}
ReverseRecursion(head, p->next);
struct List *rev;
rev = p->next;
rev->next = p;
p->next = NULL;
}
int main() {
struct List *head;
head = NULL;
int n, data, s;
printf("Enter number of nodes : ");
scanf("%d", &n);
for(int i=1; i<=n; i++) {
printf("Enter the data of node %d : ", i);
scanf("%d", &data);
ListInsert(&head,data);
}
ListPrint(&head);
printf("Reverse List Using :\n");
printf("1. Iterative Method \n");
printf("2. Recursive Method \n");
printf("Choose your option : ");
scanf("%d", &s);
switch (s)
{
case 1:
ReverseIterative(&head);
ListPrint(&head);
break;
case 2:
ReverseRecursion(&head, head);
ListPrint(&head);
break;
default:
printf("Wrong option. \n");
break;
}
return 0;
}