Abhay Hegde
Abhay Hegde

Reputation: 321

Deleting all nodes of an singly linked list

I would like to delete all the nodes present in a singly linked list by passing the headPtr. Here is my code below.

void deleteList(node *head) {
    node *curPtr, *temp;
    curPtr = temp = head;

    while ( curPtr != NULL ) {

        temp = curPtr;
        curPtr = curPtr->next;
        delete temp;
    }
    head = curPtr;
}

For a list with following nodes , 1 2 3 4 5 0 I get the following output

0 1213232 123234 2424242 24242424 24242424

Is my code correct correct ? Is there a better way to do it?

Regards

Upvotes: 0

Views: 921

Answers (2)

deb_rider
deb_rider

Reputation: 580

There may be a better way to do it. With recursion call,

void deleteList(node *head) {
    if(head!=null){
        deleteList(head->next);
        delete head;
    }
}

Hope it helped..

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

It looks good to me except the last line.

head = curPtr;

has no value whatsoever.

Upvotes: 1

Related Questions