w3resource

C Exercises: Delete alternate nodes of a singly linked list

C Singly Linked List : Exercise-33 with Solution

Write a C program to delete alternate nodes of a singly linked list.

Sample Solution:

C Code:

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

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

struct Node * newNode(int data) {
  struct Node * temp = (struct Node * ) malloc(sizeof(struct Node));
  temp -> data = data;
  temp -> next = NULL;
  return temp;
}

void printList(struct Node * head) {
  while (head != NULL) {
    printf("%d ", head -> data);
    head = head -> next;
  }
  printf("\n");
}

void delete_Alternate_Nodes(struct Node** head) {
  if (*head == NULL) return;
  struct Node* prev = *head;
  struct Node* curr = (*head)->next;
  while (curr != NULL) {
    prev->next = curr->next;
    free(curr);
    prev = prev->next;
    if (prev != NULL)
      curr = prev->next;
  }
}
int main() {
  struct Node * head = newNode(1);
  head -> next = newNode(2);
  head -> next -> next = newNode(3);
  head -> next -> next -> next = newNode(4);
  head -> next -> next -> next -> next = newNode(5);
  head -> next -> next -> next -> next -> next = newNode(6);
  head -> next -> next -> next -> next -> next -> next = newNode(7);
  printf("Original List:\n");
  printList(head);
  delete_Alternate_Nodes(&head);
  printf("\nDelete alternate nodes of the said singly linked list:\n");
  printList(head);
  return 0;
}

Sample Output:

Original List:
1 2 3 4 5 6 7 

Delete alternate nodes of the said singly linked list:
1 3 5 7 

Flowchart :

Flowchart: Delete alternate nodes of a singly linked list.
Flowchart: Delete alternate nodes of a singly linked list.

C Programming Code Editor:

Previous: Split a singly linked list into two halves.
Next: Merge alternate nodes of two linked lists.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.