+92 332 4229 857 99ProjectIdeas@Gmail.com

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


Adding node at the end of the linked list
AddNodeAtEnd() function takes the data-to be be added to the linked list as its input parameter.
Summary of AddNodeAtEnd()
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 a NULL value is assigned to the link part of the newly created node by:
node->link=NULL;
After assigning the value to the node and its link, this node have to inserted to the linked list.
While inserting this node to the linked list, 2 cases have to be dealt.
First case is that the linked list is empty, and the second case is that the linked list is not empty.
In first case when the linked list is empty, the node is assigned to the head, while in the second case, we will have to traverse the list to its end, after reaching the end, the node will be inserted at the end.
If part deals with the first case and the else part deal will the second case.

if(head==NULL)
head=node;
else
{
              Node*tptr=head;
              while(tptr->link!=NULL)
                     tptr=tptr->link;
              tptr->link=node;
       }

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);
};

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;
       }
}

int main()
{
       LinkList l;
      
       // Adding first   element to end of the linked list
       l.AddNodeAtEnd(10);
       // Adding second  element to end of the linked list
       l.AddNodeAtEnd(20);
       // Adding third   element to end of the linked list
       l.AddNodeAtEnd(30);
       // Adding fourth  element to end of the linked list
       l.AddNodeAtEnd(40);
       // Adding fifth   element to end of the linked list
       l.AddNodeAtEnd(50);
      
       _getche();
       return 0;
}

1 comments:

phantom said...

Big help thanks m8
:P