-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLrecursive.c
More file actions
45 lines (39 loc) · 881 Bytes
/
LLrecursive.c
File metadata and controls
45 lines (39 loc) · 881 Bytes
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
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createRec() {
int x;
scanf("%d", &x);
if (x == -1) return NULL;
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = x;
temp->next = createRec();
return temp;
}
void displayRec(Node* head) {
if (!head) return;
printf("%d ", head->data);
displayRec(head->next);
}
int lengthRec(Node* head) {
if (!head) return 0;
return 1 + lengthRec(head->next);
}
Node* reverseRec(Node* head) {
if (!head || !head->next) return head;
Node* rest = reverseRec(head->next);
head->next->next = head;
head->next = NULL;
return rest;
}
int main() {
Node* head = createRec();
displayRec(head);
printf("\nLength: %d\n", lengthRec(head));
head = reverseRec(head);
displayRec(head);
return 0;
}