DS Practical Slip 3 Q B

C Program to Print Alternative Nodes in Linked List Using Recursion

Linked List is an important linear data structure in C. In this program, we will print alternate (every second) nodes of a linked list using recursion in a simple and student-friendly way.


📝 Problem Statement

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


💡 Logic (Simple Steps)

  1. Create a structure for linked list node.
  2. Insert nodes into the linked list.
  3. Write a recursive function:
    • Print the current node.
    • Skip the next node.
    • Call the function for next->next.
  4. Stop recursion when node becomes NULL.

👉 Recursive idea:

print(node->data)
call function(node->next->next)

💻 Source Code (Student Friendly)

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

struct node
{
    int data;
    struct node *next;
};

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

// Function to insert at end
struct node* insert(struct node* head, int data)
{
    struct node* newnode = create(data);
    struct node* temp;

    if(head == NULL)
        return newnode;

    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);
}

int main()
{
    struct node* head = NULL;
    int n, value, i;

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

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

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

    return 0;
}

🖥️ Sample Output

Enter number of nodes: 6
Enter values:
10
20
30
40
50
60
Alternate nodes are:
10 30 50

🎓 Viva Questions with Answers

1. What is a linked list?

A linked list is a linear data structure where elements are connected using pointers.

2. What is recursion?

Recursion is a function calling itself.

3. What is the base condition in this program?

When head becomes NULL.

4. Why do we use head->next->next?

To skip one node and print alternate nodes.

5. What is the time complexity of this program?

O(n), because each node is visited once (half of them printed).

Spread the love

Leave a Comment

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

Scroll to Top