# merging two singly-linked lists in C++, help!



## Sphinx (Aug 5, 2003)

ok I have prototype for the function.

Note<T> merge(Node<T> *h1, Node<T> *h2){
Node<T> *h3 = new Node<T>;

return h3;
}

So basically h1 and h2 are parameters that point to the head of each list.
The function has to merge the two lists into h3, in proper order. Assume that h1 and h2 point to the head of lists that are ordered already.

Node<T> is a class that has member variables of 
T value;
Node *next

The function should return the point to the head of list3, the newly created merged list.


----------



## mphair (Dec 19, 2005)

h3=h1
node<T> * p = h1
//loop through h1 till you get to end.
p->next = h2

there you go...h3 will be made of h1 then h2 following


----------



## VTfletch (Jan 25, 2007)

Well that will give you list one followed by list two, but thats not what is being asked. It does have some good points though.

Here is some pseudo code for your problem tho.

LinkList H3;

if (H1 < H2)
H3.Head = H1
H1 = H1->Next
else
H3.Head = H2
H2 = H2->Next

While (lists not done)
if (H1 < H2)
H3.Next = H1
H1 = H1->Next
else
H3.Next = H2
H2 = H2->Next


----------

