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.
In this problem, we can move the head to the next position and then release the previous node.
#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; }
23 11 29 12
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.
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!