C++ Program For Writing A Function To Delete A Linked List Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report Algorithm For C++:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C++ // C++ program to delete a linked list #include <bits/stdc++.h> using namespace std; // Link list node class Node { public: int data; Node* next; }; // Function to delete the entire // linked list void deleteList(Node** head_ref) { // Define head_ref to get the // real head Node* current = *head_ref; Node* next = NULL; while (current != NULL) { next = current->next; free(current); current = next; } // Define head_ref to affect the real // head back in the caller. *head_ref = NULL; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_data) { // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list of the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node; } // Driver code int main() { // Start with the empty list Node* head = NULL; // Use push() to construct list // 1->12->1->4->1 push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); cout << "Deleting linked list"; deleteList(&head); cout << "Linked list deleted"; } // This code is contributed by rathbhupendra Output: Deleting linked list Linked list deleted Time Complexity: O(n) Auxiliary Space: O(1) Please refer complete article on Write a function to delete a Linked List for more details! Create Quiz Comment K kartik Follow 0 Improve K kartik Follow 0 Improve Article Tags : C++ Linked Lists Delete a Linked List Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like