Friday, April 11, 2014
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Solution:Straight forward comparision
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *head;
if(!l1) return l2;
if(!l2) return l1;
ListNode* n1=l1;
ListNode* n2=l2;
ListNode* nHead = new ListNode(10);
ListNode* cur = nHead;
while(n1 && n2)
{
if(n1->val > n2->val)
{
cur->next = n2;
n2 = n2->next;
}
else
{
cur->next = n1;
n1 = n1->next;
}
cur= cur->next;
}
if (!n1 && n2) cur->next = n2;
if (!n2 && n1) cur->next = n1;
cur = nHead->next;
delete nHead;
return cur;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment