Print the alternate nodes of linked list (Iterative Method) in C language

In this problem, we need to print alternate nodes from a linked list, which means printing every other node starting from the first node. The iterative method uses loops to traverse the linked list and prints nodes at even positions (0th, 2nd, 4th, etc.).

For example, if the list contains nodes 29, 34, 43, 56, and 88, the output will be alternate nodes: 29, 43, and 88.

29 34 43 56 88 Printed (alternate nodes) Skipped nodes

Syntax

void printAlternate(struct node* head);

Algorithm

  1. Initialize a counter variable to 0
  2. Traverse the linked list from head to tail
  3. For each node, check if counter is even (0, 2, 4...)
  4. If even, print the node's data
  5. Increment counter and move to next node
  6. Repeat until end of list

Example

Here's the complete implementation that prints alternate nodes from a linked list −

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

/* Structure for a node */
struct node {
    int data;
    struct node* next;
};

/* Function to print alternate nodes */
void printAlternate(struct node* head) {
    int count = 0;
    printf("Alternate nodes: ");
    while (head != NULL) {
        if (count % 2 == 0) {
            printf("%d ", head->data);
        }
        count++;
        head = head->next;
    }
    printf("<br>");
}

/* Function to add node at beginning */
void push(struct node** head, int newData) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = newData;
    newNode->next = *head;
    *head = newNode;
}

/* Function to print complete list */
void printList(struct node* head) {
    printf("Complete list: ");
    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("<br>");
}

int main() {
    struct node* head = NULL;
    
    /* Create list: 29->34->43->56->88 */
    push(&head, 88);
    push(&head, 56);
    push(&head, 43);
    push(&head, 34);
    push(&head, 29);
    
    printList(head);
    printAlternate(head);
    
    return 0;
}
Complete list: 29 34 43 56 88 
Alternate nodes: 29 43 88 

How It Works

  • The count variable tracks the position of each node (0, 1, 2, 3...)
  • When count % 2 == 0, it means we're at an even position (0th, 2nd, 4th...)
  • These positions correspond to alternate nodes that need to be printed
  • The counter increments for every node, but printing happens only for even positions

Conclusion

The iterative approach to print alternate nodes uses a simple counter-based logic with O(n) time complexity and O(1) space complexity. This method efficiently traverses the list once and prints every second node starting from the head.

Updated on: 2026-03-15T11:57:39+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements