# C++ : Concatenating two linked lists in C++

May 30, 2017 20642

### Previous:

Make sure that you are familiar with the concepts explained in the post(s) mentioned above before proceeding further.

We will proceed further by taking the linked list we made in the previous post

#include <iostream>

using namespace std;

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

{
private:
public:
{
tail = NULL;
}

{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;

{
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
};

int main()
{
return 0;
}


Concatenating or joining two linked lists is not at all a difficult task. We just need to follow some very simple steps and the steps to join two lists (say ‘a’ and ‘b’) are as follows:

1. Traverse over the linked list ‘a’ until the element next to the node is not NULL.
2. If the element next to the current element is NULL (a->next == NULL) then change the element next to it to ‘b’ (a->next = b).

That’s it. Let’s code up these steps.

.

void concatenate(struct node *a,struct node *b)
{
if (a->next == NULL)
a->next = b;
else
concatenate(a->next,b);
}


Here, we are traversing over the article using recursion as explained in the article “Linked list traversal using while loop and recursion”. We are firstly checking if the next node (a->next) is NULL or not. If it is NULL, then we are just changing its value from NULL to ‘b’ (a->next = b) and if it is not then we are calling the ‘concatenate’ function again with the next element to traverse over the list.

So, the whole code is:

#include <iostream>

using namespace std;

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

{
private:
public:
{
tail = NULL;
}

{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;

{
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}

{
}

{
{
cout << "NULL" << endl;
}
else
{
}
}

static void concatenate(node *a,node *b)
{
if( a != NULL && b!= NULL )
{
if (a->next == NULL)
a->next = b;
else
concatenate(a->next,b);
}
else
{
cout << "Either a or b is NULL\n";
}
}
};

int main()
{
return 0;
}


### The simpler way

We can use the above method even when we don't have the record of the 'tail'. When we keep the record of the 'tail', we can simply do a->tail->next = b->head

### Next:

Liked the post?
Developer and founder of CodesDope.
Editor's Picks