+92 332 4229 857 99ProjectIdeas@Gmail.com

How to add node at the start of the singly linked list (C++)


Adding node at the start of the linked list
AddNodeAtStart() function takes the data-to be be added to the linked list as its input parameter.
Summary of AddNodeAtStart()
First of all a new node is created by the statement:
Node*node=new Node();
When a new node is created, a constructor of the structure Node will be called and it assigns NULL to both the data and the link of the newly created node.
After that the data is assigned to the newly created node by the statement:
node->data=_data;
And the head is assigned to the link part of the newly created node by:
node->link=head;
Now the newly created node is assigned to the head by:
       head=node;
This means that the head is pointing towards the newly created node and the link part of this node is pointing to the previous linked list,in this way a node is added to the start of the linked list.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

struct Node
{
public:
       int data;
       Node*link;
      
       Node();
};

Node::Node()
{
       data=0;
       link=NULL;
}

class LinkList
{
public:
       Node*head;
       LinkList();
       void AddNodeAtEnd(int);
       void AddNodeAtStart(int);
};

LinkList::LinkList()
{
       head=NULL;
}

void LinkList::AddNodeAtEnd(int _data)
{
       Node*node=new Node();
       node->data=_data;
       node->link=NULL;
      
       if(head==NULL)
              head=node;
       else
       {
              Node*tptr=head;
              while(tptr->link!=NULL)
                     tptr=tptr->link;
              tptr->link=node;
       }
}

void LinkList::AddNodeAtStart(int _data)
{
       Node*node=new Node();
       node->data=_data;
       node->link=head;
       head=node;
}

int main()
{
       LinkList l;
      
       // Adding first  element to the linked list
       l.AddNodeAtEnd(50);
       // Adding second element to the linked list
       l. AddNodeAtEnd(60);
       // Adding third  element to the linked list
       l.AddNodeAtEnd(70);
       // Adding fourth element to the linked list
       l.AddNodeAtEnd(80);
       // Adding fifth  element to the linked list
       l.AddNodeAtEnd(90);
       // Adding element to the start of the linked list
       l.AddNodeAtStart(40);
       // Adding element to the start of the linked list
       l.AddNodeAtStart(30);
       // Adding element to the start of the linked list
       l.AddNodeAtStart(20);
       // Adding element to the start of the linked list
       l.AddNodeAtStart(10);

       _getche();
       return 0;
}

0 comments: