-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingly_list_reverse_recursion.c
92 lines (80 loc) · 2.16 KB
/
singly_list_reverse_recursion.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
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createList() {
struct Node* head = NULL, * temp = NULL;
int n, data;
printf("Enter the number of nodes: ");
scanf("%d", &n);
if (n <= 0) return NULL;
for (int i = 0; i < n; i++) {
printf("Enter data for node %d: ", i + 1);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
temp = head;
} else {
temp->next = newNode;
temp = temp->next;
}
}
return head;
}
void display(struct Node* head) {
struct Node* temp = head;
if (temp == NULL) {
printf("List is empty.\n");
return;
}
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
struct Node* reverseRecursively(struct Node* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct Node* newHead = reverseRecursively(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
int main() {
struct Node* head = NULL;
int choice;
do {
printf("\nMenu:\n");
printf("1. Create List\n");
printf("2. Display List\n");
printf("3. Reverse List\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
head = createList();
break;
case 2:
display(head);
break;
case 3:
head = reverseRecursively(head);
printf("List reversed successfully.\n");
break;
case 4:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Try again.\n");
}
} while (choice != 4);
return 0;
}