We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Very nice! Here is C solution using while loop.
Not as elegant but easier to understand:
Node* MergeLists(Node *headA, Node* headB)
{
if (headA == NULL && headB == NULL) {
return NULL;
}
if (headA == NULL) {
return headB;
}
if (headB == NULL) {
return headA;
}
// Ensure that list A starts with the smaller number
if (headA->data > headB->data) {
Node *tmp = headB;
headB = headA;
headA = tmp;
}
Node *listHead = headA;
while (headB) {
// Advance through nodes in list A until the next node
// has data bigger than data at current node of list B
while (headA->next != NULL &&
headB->data > headA->next->data) {
headA = headA->next;
}
// Insert current node in list B into list A
Node* nextB = headB->next;
headB->next = headA->next;
headA->next = headB;
headB = nextB;
}
return listHead;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
Very nice! Here is C solution using while loop. Not as elegant but easier to understand: