Home  >  Article  >  Backend Development  >  Delete the first node of a linked list using C++

Delete the first node of a linked list using C++

WBOY
WBOYforward
2023-09-22 09:17:081415browse

Delete the first node of a linked list using C++

Given a linked list, we need to delete its first element and return the pointer to the head of the new linked 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 the head to the second element and return the head.

Method to find the solution

In this problem, we can move the head to the next position and then release 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

Above code description

We just need to move the head to the next element in the program and 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 does not depend on the given input, which is the best complexity we can achieve.

Conclusion

In this article, we solved a problem of deleting the first node of a linked list. We also learned a C program for this problem and our complete approach to solving it. We can write the same program in other languages ​​such as C, java, python and other languages. We hope this article was helpful to you.

The above is the detailed content of Delete the first node of a linked list using C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete