Data Structure Slip No_5B

 #include <stdio.h>

#include <stdlib.h>

// Definition of a Node

struct Node 

{

    int data;

    struct Node* next;

};

// Function to insert a digit as a new node at the end of the linked list

void insertDigit(struct Node** head, int digit) 

{

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = digit;

    newNode->next = NULL;

    if (*head == NULL) 

    {

        *head = newNode;

    } 

    else 

    {

        struct Node* current = *head;

        while (current->next != NULL) 

        {

            current = current->next;

        }

        current->next = newNode;

    }

}

// Function to print the linked list

void printLinkedList(struct Node* head)

     {

    while (head != NULL) 

    {

        printf("%d ", head->data);

        head = head->next;

    }

    printf("\n");

}

// Function to free the memory occupied by the linked list

void freeLinkedList(struct Node* head) 

{

    while (head != NULL)

    {

        struct Node* temp = head;

        head = head->next;

        free(temp);

    }

}

int main() 

{

    struct Node* head = NULL;

    int number;

    printf("Enter a number: ");

    scanf("%d", &number);


    // Extract digits and insert them into the linked list

    while (number > 0) 

   {

        int digit = number % 10;

        insertDigit(&head, digit);

        number /= 10;

    }

    printf("Linked list containing individual digits of the number:\n");

    printLinkedList(head);


    // Free memory

    freeLinkedList(head);

    return 0;

}

Output:

Enter a number: 47215
Linked list containing individual digits of the number:
5 1 2 7 4 

No comments:

Post a Comment