LINK LIST : Adding, Deleting and Displaying the Nodes from the List using UDFs in CPP

#include<iostream.h>
#include<conio.h>

class List {
            private:
            struct node{
                        int data;
                        node * next;
            }*nodePtr, *head, *curr, *temp;

            public:
            List();
            void AddNode(int addData);
            void DeleteNode(int delData);
            void PrintList();
};

List::List() {
            head=NULL;
            curr=NULL;
            temp=NULL;
}

void List::AddNode(int addData) {
            node* n = new node;
            n->next = NULL;
            n->data = addData;

            if(head!=NULL)            {
                        curr=head;
                        while(curr->next!=NULL) {
                                    curr=curr->next;
                        }
                        curr->next=n;
            }
            else
                        head=n;
}

void List::DeleteNode(int delData) {
            node* delPtr;
            delPtr=NULL;
            temp=head;
            curr=head;
            while(curr!=NULL && curr->data!=delData) {
                        temp=curr;
                        curr=curr->next;
            }

            if(curr==NULL)            {
                        cout<<delData<<" was not in the list.\n";
                        delete delPtr;  //as program will not take any value.
            }
            else {
                        delPtr=curr;
                        curr=curr->next;
                        temp->next=curr;

                        if(delPtr==head) {
                                    head=head->next;
                                    temp=NULL;
                        }
                        delete delPtr;
                        cout<<"The value " <<delData<<" has been deleted from the list.\n";
            }
}

void List::PrintList() {
            curr=head;
            while(curr!=NULL) {
                        cout<<curr->data<<" -> ";
                        curr=curr->next;
            }
            cout<<endl;
}

int main() {
            clrscr();
            List obj;

            //Adding the nodes in the list.
            obj.AddNode(10);       
            obj.AddNode(20);
            obj.AddNode(30);
            obj.AddNode(40);
            obj.AddNode(50);

            //Printing the List.
            obj.PrintList();

            //Deleting the Nodes from the List.
            obj.DeleteNode(10);   //value which is the list at begining.
            obj.DeleteNode(45);   //value which not in List.

            //Printing the List.
            obj.PrintList();
            getch();
            return 0;
}

No comments

Post your comments

Powered by Blogger.