Delete alternate nodes of a Linked List in C++


In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list.

Let's see the steps to solve the problem.

  • Write struct with data and next pointer.

  • Write a function to insert the node into the singly linked list.

  • Initialize the singly linked list with dummy data.

  • Iterate over the singly linked list.

  • Delete alternate node by maintaining the previous node.

  • Write a function to delete the node. Consider the following three cases while deleting the node.

    • If the node is head node, then move the head to next node.

    • If the node is middle node, then link the next node to the previous node

    • If the node is end node, then remove the previous node link. Let's see the code.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *next;
};
void deleteAlternateNodes(Node *head) {
   if (head == NULL)
      return;
   Node *prev = head;
   Node *node = head->next;
   while (prev != NULL && node != NULL) {
      prev->next = node->next;
      free(node);
      prev = prev->next;
      if (prev != NULL) {
         node = prev->next;
      }
   }
}
void insertNode(Node** head_ref, int new_data) {
   Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
void printLinkedList(Node *node) {
   while (node != NULL) {
      cout << node->data << " -> ";
      node = node->next;
   }
}
int main() {
   Node* head = NULL;
   insertNode(&head, 1);
   insertNode(&head, 2);
   insertNode(&head, 3);
   insertNode(&head, 4);
   insertNode(&head, 5);
   insertNode(&head, 6);
   cout << "Linked List before deletion:" << endl;
   printLinkedList(head);
   deleteAlternateNodes(head);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

Linked List before deletion:
6 -> 5 -> 4 -> 3 -> 2 -> 1 ->
Linked List after deletion:
6 -> 4 -> 2 ->

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 30-Dec-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements