Following is a function for deleting the entire list by accessing the head
pointer to the 1st node:
void deleteList(Node *head)
{
while (head != nullptr)
{
Node *temp = head;
head = head->next;
delete temp;
}
}
Detailed program:
struct Node {
int data;
Node* next;
};
void traverseList(Node* head) {
while (head != nullptr) {
cout << head->data << endl;
head = head->next;
}
}
void deleteList(Node *head)
{
while (head != nullptr)
{
Node *temp = head;
head = head->next;
delete temp;
}
}
int main() {
Node* head = new Node();
head->data = 10;
head->next = new Node();
head->next->data = 20;
head->next->next = new Node();
head->next->next->data = 30;
traverseList(head);// traversing list before deletion
deleteList(head);
traverseList(head);// traversing list after deletion
}
Even after deleting the list, the program can access the list again, how is that possible?
Is there any other way to delete the list?
Is the delete
keyword working properly? Or, do we not know how to delete the node and how the delete
keyword works?
Even after deleting the list, the program can access the list again, how is that possible?
Deleting an object invalidates any pointer that is pointing at it. Accessing an object through an invalid pointer results in undefined behaviour. When the behaviour of the program is undefined, "anything" is possible. You should avoid having undefined behaviour in your program. Refrain from attempting to access memory through invalid pointers.
Is the
delete
keyword working properly?
Yes.