All About C++

Get Pure Concepts of C++

Wednesday 10 February 2016

how To add data in singly link list in data structure with the example of source code

To add data in singly link list

Using following technique we can easily add data in single link list

#include<iostream>
#include<conio.h>
using namespace std;
struct link
{
    int data;
    link *next;
};
//Defined a Structure


class List      // where we create the links and combin them in a list
{
private:
            link *first;         // Head start or here its name is first...
public:
            List()
                        {
            first=NULL;          // null as link list is empty
            }
            void add(int d)
                        {
            link *ptr,*temp;
            if(first==NULL)// will execute only once as when we will add first element as first is null.
            {
                        first=new link;     // vvimp steps. Create a structure, and reference will updated have a close look at first.
                        first->data=d;      // assign value of d come from main function to first of data.
                        first->next=NULL;   // Assign null
            }
            else
            {
                        ptr=first;
                        while(ptr->next!=NULL)
        {
                        ptr=ptr->next;// same as increment statement as it moves toward null
        }
        temp=new link;            // these three lines add new elements
                        temp->data=d;
                        temp->next=NULL;   
             ptr->next=temp;           // link the nodes with previous ones....
            }
};

int main(){
    List l;
            l.add(20);
            l.add(30);
            l.add(40);
            l.add(50);
             getch();

}