54 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
			
		
		
	
	
			54 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
// 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);
 | 
						|
}
 |