SYBCom(CA) DS Practical Slip 3 Q.B

Write C Program to print alternative nodes in linked list using recursion.

#include <stdio.h>
#include <stdlib.h>

// Structure of Node
struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// Function to insert node at end
struct Node* insertEnd(struct Node* head, int data) {
    struct Node* newNode = createNode(data);

    if (head == NULL)
        return newNode;

    struct Node* temp = head;
    while (temp->next != NULL)
        temp = temp->next;

    temp->next = newNode;
    return head;
}

// Recursive function to print alternate nodes
void printAlternate(struct Node* head) {
    if (head == NULL)
        return;

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

    if (head->next != NULL)
        printAlternate(head->next->next);
}

// Main function
int main() {
    struct Node* head = NULL;
    int n, value;

    printf("Enter number of nodes: ");
    scanf("%d", &n);

    printf("Enter %d values:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &value);
        head = insertEnd(head, value);
    }

    printf("Alternate nodes are:\n");
    printAlternate(head);

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top