Upload files to "DS/C/Lab/Week7"
This commit is contained in:
parent
7a2498b4ff
commit
75507b7abc
4 changed files with 336 additions and 0 deletions
54
DS/C/Lab/Week7/RecursiveLL.c
Normal file
54
DS/C/Lab/Week7/RecursiveLL.c
Normal file
|
@ -0,0 +1,54 @@
|
|||
// Write recursive functions for i) Creating a linked list ii) Traversing a linked list.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
struct node {
|
||||
int data;
|
||||
struct node *link;
|
||||
};
|
||||
|
||||
struct node *create(int);
|
||||
void traverse(struct node *);
|
||||
void freeList(struct node *);
|
||||
|
||||
int main() {
|
||||
struct node *list;
|
||||
int n;
|
||||
printf("Enter the number of nodes: ");
|
||||
scanf("%d", &n);
|
||||
list = create(n);
|
||||
printf("Linked list created:\n");
|
||||
traverse(list);
|
||||
freeList(list);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct node *create(int n) {
|
||||
struct node *temp;
|
||||
if (n == 0)
|
||||
return NULL;
|
||||
temp = (struct node *)malloc(sizeof(struct node));
|
||||
if (temp == NULL) {
|
||||
printf("Memory allocation failed\n");
|
||||
exit(1);
|
||||
}
|
||||
printf("Enter data: ");
|
||||
scanf("%d", &temp->data);
|
||||
temp->link = create(n - 1);
|
||||
return temp;
|
||||
}
|
||||
|
||||
void traverse(struct node *list) {
|
||||
if (list == NULL)
|
||||
return;
|
||||
printf("%d ", list->data);
|
||||
traverse(list->link);
|
||||
}
|
||||
|
||||
void freeList(struct node *list) {
|
||||
if (list == NULL)
|
||||
return;
|
||||
freeList(list->link);
|
||||
free(list);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue