Remove First Node of the Linked List using C++

C++Server Side ProgrammingProgramming

Given a linked list, we need to remove its first element and return the pointer to the head of the new list.

Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output : 2 -> 3 -> 4 -> 5 -> NULL

Input : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL
Output : 4 -> 6 -> 8 -> 33 -> 67 -> NULL

In the given problem, we need to remove the first node of the list and move our head to the second element and return the head.

Approach to find The Solution

In this problem, we can move the head to the next location and then free the previous node.

Example

#include <iostream>
using namespace std;
/* Link list node */
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** head_ref, int new_data) { // pushing the data into the list
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main() {
   Node* head = NULL;
   push(&head, 12);
   push(&head, 29);
   push(&head, 11);
   push(&head, 23);
   push(&head, 8);
   auto temp = head; // temp becomes head
   head = head -> next; // our head becomes the next element
   delete temp; // we delete temp i.e. the first element
   for (temp = head; temp != NULL; temp = temp->next) // printing the list
      cout << temp->data << " ";
   return 0;
}

Output

23 11 29 12

Explanation of the above code

We just need to shift the head to its next element in this program and then delete the previous element and then print the new list. The overall time complexity of the given program is O(1) which means that our program doesn’t depend on the given input, and it is the best complexity we can achieve.

Conclusion

In this article, we solve a problem to Remove the first node of the linked list. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.

raja
Updated on 26-Nov-2021 11:18:33

Advertisements