Saturday, April 23, 2011

Add node at the end of linked list

Given a singly linked list and node to insert, insert given node at the end of link list.

Below is the code to add node at the end of the linked list:

Here node is of form:

struct Node {
    int data;
    Node * next;
};

Node* AddAtEnd(Node* head, int value)
{
if(head == NULL)
{
head = new Node;
head->next=NULL;
head->data= value;
return head;     
}
Node* node = head;
while( node->next!=NULL)
node = node->next;

Node* tmp = new Node;
tmp->next= NULL;
tmp->data=value;
node->next = tmp;
return head;
}

No comments:

Post a Comment