#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

#### Categories

Member Posts: 20
this is the function to merge two linked lists of integers that are sorted
into ascending order...
the result is the third linked lists that is sorted combination of original
two...

please take a look and give some help thanx...

[code]
void merge(const List& a, const List& b){

Node* curr = a.head; //to traverse the first list
Node* comp = b.head; //to traverse the second list
Node* head = new ListNode; //creating the third list
Node* temp = head; //to traverse the third list

while (curr->next!=NULL && comp->next!=NULL){
// but what if there are different # of Nodes in the lists???
if (curr->item <= comp->item){
temp->item = curr->item;
curr = curr->next;
}
else {
temp->item = comp->item;
comp = comp->next;
}
temp->next = new ListNode;
temp = temp->next;
}
[/code]

• Member Posts: 438
[italic]
// but what if there are different # of Nodes in the lists???
[/italic]

After the "main" while loop, you have to append these to loops:

[code]
[blue]while[/blue] (curr->next != NULL)
{
temp->item = curr->item;
curr = curr->next;
temp->next = [blue]new[/blue] ListNode;
temp = temp->next;
}

[blue]while[/blue] (comp->next != NULL)
{
temp->item = comp->item;
comp = comp->next;
temp->next = [blue]new[/blue] ListNode;
temp = temp->next;
}
[/code]

Please not that, not only my loops but also after yours, temp->next has been created, but is unused. You would have to delete it at the end of the function.

Was that all that was wrong with your function or was there anything else?

---
[b]edx[/b] - Member of [blue][b]CodeForce[/b][/blue] (http://codeforce.d2g.com)

• USAMember Posts: 4,496 ✭✭

____ < http://forcoder.org /> free video tutorials and ebooks about / Java C MATLAB Visual Basic .NET Assembly PL/SQL Scratch Ruby Swift Delphi JavaScript Go C++ R Python Perl Objective-C PHP Visual Basic C# Bash SAS Julia Crystal Scala Prolog Awk Ada Dart ML D Lua Fortran COBOL F# Clojure Alice Kotlin VBScript Apex Hack Logo ABAP Rust LabVIEW Erlang Lisp Scheme Transact-SQL FoxPro / ___