Tuesday 19 May 2015

Implementation of link list using c++

#include<iostream>

using namespace std;

struct node
{
        int data;
        struct node *link;
};

typedef struct node NODE;

class list
{
        NODE *start;
        public:
                list()
                {
                        start=NULL;
                }
                void insert_front();
                void delete_front();
                void display();
};

void list::insert_front()
{
        NODE *temp;
        int item;
        temp=new NODE;
        if(temp==NULL)
        {
                cout<<"memory allocation failed";
                return;
        }
        cout<<"\nenter the element:\t";
        cin>>item;
        temp->data=item;
        temp->link=start;
        start=temp;
}

void list::delete_front()
{
        NODE *temp;
        if(start==NULL)
        {
                cout<<"\nlist is empty";
                return;
        }
        temp=start;
        cout<<"element deleted:\t"<<temp->data;
        start=start->link;
        delete temp;
}

void list::display()
{
        NODE *temp;
        temp=start;
        cout<<"\ncontents of list\n";
        while(temp!=NULL)
        {
                cout<<temp->data<<"->";
                temp=temp->link;
        }
        cout<<"null\n";
}

int main()
{
        list l;
        int ch;
        system("clear");

        while(1)
        {
                cout<<"\n\n1.insert\n2.delete\n3.display\n4.exit\n\nenter your choice:\t";
                cin>>ch;
                switch(ch)
                {
                        case 1:
                                l.insert_front();
                                break;
                        case 2:
                                l.delete_front();
                                break;
                        case 3:
                                l.display();
                                break;
                        default:exit(0);
                }
        }
        return 0;
}

No comments:

Post a Comment