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

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

WBOY
Release: 2023-09-22 09:17:08
forward
1482 people have browsed it

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
Copy after login

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;
}
Copy after login

Output

23 11 29 12
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template