You are given 2 sorted linked lists of integers. You need to merge then 2 lists to get a sorted list
pseudo code: assuming ascending.
[code:1]ptra=head of A; prtb=head of B; ptrc=new head;
if (ptra->val > ptrb->val) { ptrc = ptra; ptra= ptra->next; } else { ptrc = ptrb; ptrb=ptrb->next; }
temp=ptrc while (ptra && ptrb) { if (ptra->val > ptrb->val) { temp->next = ptra; ptra= ptra->next; } else { temp->next=ptrb; ptrb=ptrb->next; } }
//if any list remains, append if (ptra) temp->next=ptra; if (ptrb) temp->next=ptrb; [/code:1]
that should do the job in O(N) and no extra space
Merge two sorted linked list
pseudo code:
assuming ascending.
[code:1]ptra=head of A;
prtb=head of B;
ptrc=new head;
if (ptra->val > ptrb->val) { ptrc = ptra; ptra= ptra->next; }
else { ptrc = ptrb; ptrb=ptrb->next; }
temp=ptrc
while (ptra && ptrb)
{
if (ptra->val > ptrb->val) { temp->next = ptra; ptra= ptra->next; }
else { temp->next=ptrb; ptrb=ptrb->next; }
}
//if any list remains, append
if (ptra) temp->next=ptra;
if (ptrb) temp->next=ptrb;
[/code:1]
that should do the job in O(N) and no extra space