Tuesday, August 31, 2010

Delete a linked list using recursion in C++

#include < iostream >
using namespace std;

struct Node{
    int num;
    Node* next;
};

//Here address of pointer to the list is passed so that head of the  list  will not be a local variable.

void DeleteListRecursion(Node*& list){
    if(list == NULL)
        return;
    else
     DeleteListRecursion(list->next);
     delete(list);
     list = NULL;
}



Node* Insert(int number, Node* list){
    Node* node = new Node;
    node->num = number;
    node->next = list;
    return node;
}

//TEST

int main(){
       
    Node* list = NULL;

    list = Insert(5,list);
    list = Insert(7,list);
    list = Insert(9,list);
    list = Insert(4,list);
    list = Insert(6,list);
    list = Insert(3,list);
   
    DeleteListRecursion(list);

    return 0;
}

No comments:

Post a Comment