Tuesday, 12 September 2017

TO INSERT A NEW NODE IN THE BEGINNING AND END OF THE SINGLY LINK LIST

A Linked List is an ordered collections of data in which each element ( Node) contains a minimum of two values, Data and Link to its successor node. A list with one link field using which every element is associated to its successor is known as a singly linked list (SLL). In a linked list, before adding any node to the list, a memory space for that node must be allocated. 

#include <iostream>
using namespace std;
  struct node
  {
    int data;
    node *next;
  };
  class list
  {
    public:
    node *head, *tail;
    public:
    list()
    {
      head=NULL;
      tail=NULL;
    }
    
void createnode(int value)
    {
      node *temp=new node;
      temp->data=value;
      temp->next=NULL;
      if(head==NULL)
      {
        head=temp;
        tail=temp;
        temp=NULL;
      }
      else
      {
          temp->next=head;
          head=temp;
          temp=NULL;
     
      }
    }
      void display()
  {
    node *temp=new node;
    temp=head;
    while(temp!=NULL)
    {
      cout<<temp->data<<"t";
      temp=temp->next;
    }
  } 
  };
 int main()
{
    list a;
    int n;
    for(int i=1;i<=5; i++)
    {
        cin>>n;
    a.createnode(n);
     
    }
    a.display();
    return 0;
}

TO INSERT A NEW NODE IN THE END OF THE SINGLY LINK LIST
#include <iostream>



using namespace std;
struct node
{
    int data;
    node *next;
};
class list
{
    public:
    node *head, *tail;
    list()
    {
        head=NULL;
        tail=NULL;
    }
void createnode(int value)
{
    node *temp=new node;
    temp->data=value;
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
        tail=temp;
        temp=NULL;
    }
    else
    {
        tail->next=temp;
        tail=temp;
        temp=NULL;
    }
}
void display()
{
    node *temp=new node;
    temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data<<"\t";
        temp=temp->next;
    }
}
};
int main() {
list a;
int n;
for(int i=1;i<=5;i++)
{
    cin>>n;
    a.createnode(n);
}
a.display();
return 0;
}


Thanks

Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput