Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 212

What is the best way to merge 2 single linked list (list1 and list 2) into a 3rd list (list3).  The lists are of type INT.  These single linked list are not arrays and are created with a Struct and pointers.
0
RickHancock
• 2
1 Solution

Commented:
You'd have the last entry of List1 point to the head (1st) entry of List2, e.g.

struct ListEntry {

int data;
struct ListEntry* pNext;
};

// go to the end of List1
while ( List1->pNext != NULL) List1 = List1->pNext;

// Set 'pNext' to the head of list2 to join them

List1->pNext = List2;
0

Commented:
Ooops, I forgot, then:

LisEntry* List3 =GetHeadOfList1(); // that now resembles the joined list.
0

Commented:
If the lists were sorted you need something like that:

struct Node
{
int data;
Node* pNext;
Node(int d) : data(d), pNext(NULL) {}
~Node() { delete pNext; }
};

class SList
{
Node* pLast;
public:
{
Node* p = new Node(d);
else
{
pLast->pNext = p;
pLast = p;
}
}
SList(const SList& list1, const SList2& list2)
{
while (p1 != NULL || p2 != NULL)
{
if (p1 == NULL && p2 == NULL)
{
if (p1->data < p2->data)
{
p1 = p1->pNext;
}
else
{
p2 = p2->pNext;
}
}
else if (p1 != NULL)
{
p1 = p1->pNext;
}
else
{