Delete a Node from linked list without head pointer in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to delete a node without head pointer in 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.

  • Take a node from the linked list using the next pointer.

  • Move the delete node to the next node.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void deleteNodeWithoutHead(struct Node* deletingNode) {
   if (deletingNode == NULL) {
      return;
   }
   else {
      if (deletingNode->next == NULL) {
         cout << "Can't delete last node without head" << endl;
         return;
      }
      struct Node* temp = deletingNode->next;
      deletingNode->data = temp->data;
      deletingNode->next = temp->next;
      free(temp);
   }
}
void printLinkedList(Node* head) {
   Node* temp = head;
   while (temp) {
      cout << temp->data << " -> ";
      temp = temp->next;
   }
}
void insertNode(struct Node** head_ref, int new_data) {
   struct Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main() {
   struct 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);
   Node* del = head->next;
   deleteNodeWithoutHead(del);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   return 0;
}

Output

If you run the above code, then you will get the following result.

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

Conclusion

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

raja
Published on 30-Dec-2020 06:42:50
Advertisements