w3resource

C Exercises: Remove elements with odd indices from a linked list

C Singly Linked List : Exercise-25 with Solution

Write a C program that removes elements with odd indices from a singly linked list.

Sample Solution:

C Code:

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

// Definition for singly-linked list.
struct Node {
    int data;
    struct Node* next;
};

// Remove elements with odd indices 
void removeOddIndices(Node** head) {
    Node* current = *head;
    Node* prev = NULL;
    int count = 1;

    while (current != NULL) {
        if (count % 2 == 1) {
            if (prev == NULL) {
                *head = current->next;
            } else {
                prev->next = current->next;
            }
            Node* temp = current;
            current = current->next;
            free(temp);
        } else {
            prev = current;
            current = current->next;
        }
        count++;
    }
}

// Insert a new node at the beginning of the linked list
void push(Node** head, int data) {
    Node* new_node = (Node*) malloc(sizeof(Node));
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
}

// Print the linked list
void printList(Node* head) {
    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}
// Test the function
int main() {
    Node* head = NULL;

    // Create a linked list
    push(&head, 1);
    push(&head, 2);
    push(&head, 3);
    push(&head, 4);
    push(&head, 5);
    push(&head, 6);
    push(&head, 7);

    printf("Original linked list:\n");
    printList(head);
    removeOddIndices(&head);
    printf("\nLinked list after removing odd indices:\n");
    printList(head);
    printf("\n");
    return 0;
}

Sample Output:

Original linked list:
7 6 5 4 3 2 1

Linked list after removing odd indices:
6 4 2

Flowchart :

Flowchart: Remove elements with odd indices from a linked list.
Flowchart: Remove elements with odd indices from a linked list.

C Programming Code Editor:

Previous: Change Kth node from beginning to end in a linked list.
Next: Remove elements with even indices from a linked list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.