Product of the alternate nodes of linked list

Given a linked list with n nodes, the task is to find the product of alternate nodes. The program calculates the product of nodes at positions 1, 3, 5, etc. (starting from position 1) without modifying the linked list structure.

Syntax

void calculateAlternateProduct();
struct node {
    int data;
    struct node *next;
};

Example

Input: 10 20 30 40 50 60
Output: 15000

In the above example, starting from the first node (10), alternate nodes are 10, 30, 50 and their product is 10 × 30 × 50 = 15000.

10 20 30 40 50 60 Alternate nodes Other nodes

Algorithm

The approach uses a simple traversal technique −

  • Start from the head node (first alternate node)
  • Initialize product with the first node's data
  • Move to every second node using temp = temp->next->next
  • Multiply the product with each alternate node's data

Implementation

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

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

void insert(int val) {
    struct node* newnode = (struct node*)malloc(sizeof(struct node));
    if (newnode == NULL) {
        printf("Memory allocation failed<br>");
        return;
    }
    newnode->data = val;
    newnode->next = NULL;
    
    if (head == NULL) {
        head = newnode;
    } else {
        struct node* temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newnode;
    }
}

void display() {
    if (head == NULL) {
        printf("List is empty<br>");
        return;
    }
    
    struct node* temp = head;
    printf("Linked list: ");
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("<br>");
}

void calculateAlternateProduct() {
    if (head == NULL) {
        printf("List is empty<br>");
        return;
    }
    
    struct node* temp = head;
    int product = temp->data;
    
    while (temp != NULL && temp->next != NULL && temp->next->next != NULL) {
        temp = temp->next->next;
        product = product * temp->data;
    }
    
    printf("Product of alternate nodes: %d<br>", product);
}

int main() {
    head = NULL;
    
    insert(10);
    insert(20);
    insert(30);
    insert(40);
    insert(50);
    insert(60);
    
    display();
    calculateAlternateProduct();
    
    return 0;
}
Linked list: 10 20 30 40 50 60 
Product of alternate nodes: 15000

Key Points

  • The algorithm has O(n) time complexity and O(1) space complexity
  • Proper null checks prevent segmentation faults when traversing the list
  • Memory allocation is checked to ensure successful node creation

Conclusion

Finding the product of alternate nodes in a linked list is efficiently achieved by traversing every second node. The algorithm maintains constant space usage while visiting only the required nodes.

Updated on: 2026-03-15T12:06:08+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements