In this shot, we will create a function to delete the head node of a singly linked list in C++.
Below is the standard implementation of a singly linked list in C++. We will pass the object of the LinkedList
class to our delete_head
function, which will return a linked list with the original head node deleted.
#include <iostream>using namespace std;// Making a node struct containing a data int and a pointer// to another nodestruct Node {int data;Node *next;};class LinkedList{public:// Head pointerNode* head;// default constructor. Initializing head pointerLinkedList(){head = NULL;}// inserting elements (At start of the list)void insert(int val){// make a new nodeNode* new_node = new Node;new_node->data = val;new_node->next = NULL;// If list is empty, make the new node, the headif (head == NULL)head = new_node;// else, make the new_node the head and its next, the previous// headelse{new_node->next = head;head = new_node;}}// loop over the list. return true if element foundbool search(int val){Node* temp = head;while(temp != NULL){if (temp->data == val)return true;temp = temp->next;}return false;}void remove(int val){// If the value to be deleted is at headif (head->data == val){delete head;head = head->next;return;}// If there is only one element in the listif (head->next == NULL){// If the head is to be deleted. Assign null to the headif (head->data == val){delete head;head = NULL;return;}// else print, value not foundcout << "Value not found!" << endl;return;}// Else loop over the list and search for the node to deleteNode* temp = head;while(temp->next!= NULL){// When node is found, delete the node and modify the pointersif (temp->next->data == val){Node* temp_ptr = temp->next->next;delete temp->next;temp->next = temp_ptr;return;}temp = temp->next;}// Else, the value was neve in the listcout << "Value not found" << endl;}void display(){Node* temp = head;while(temp != NULL){cout << temp->data << " ";temp = temp->next;}cout << endl;}};// This is the function we are interested in. It takes in a LinkedList object and// returns a Node pointer to the head of a linked list with the original head deletedNode* delete_head(LinkedList lst){if (lst.head != NULL){// Move the head pointer to the next nodeNode* temp = lst.head;// Move head one node aheadlst.head = lst.head->next;// Delete previous headdelete temp;// Return new headreturn lst.head;}}int main() {LinkedList l;// inserting elements into linked list ll.insert(6);l.insert(9);l.insert(1);l.insert(3);l.insert(7);// Displaying current linked listcout << "Current Linked List: "<<endl;l.display();// Deleting head of linked listl.head = delete_head(l);// Displaying linked list after deleting head nodecout << "Linked list after deleting head node:"<<endl;l.display();}
Free Resources