logo CodeStepByStep logo

linkedListMystery5

Language/Type: C++ linked lists pointers

Consider the following two linked lists of ListNode objects, with pointers named front1 and front2 that point to the first node of each list:

front1 ->  2 ->  5 ->  3 ->  8 -> 15 ->  9 /
front2 ->  4 ->  6 -> 12 ->  7 -> 16 -> 99 /

Write the final state of the two linked lists after the following code runs. If a given node is removed from either list and not in either list at the end, you don't need to draw that node, only the ones that remain reachable in the original lists. Write your answer in this format, without the quotes: "front1 -> 10 -> 20 -> 30 /".

void linkedListMystery(ListNode*& front1, ListNode*& front2) {
    while (front1->data < front2->data) {
        ListNode* trash = front1;
        front1 = front1->next;
        delete trash;
    }

    ListNode* curr1 = front1;
    ListNode* curr2 = front2;
    while (curr1->next != nullptr && curr2->next != nullptr) {
        if (curr1->next->data < curr2->next->data) {
            ListNode* temp = curr1->next;
            curr1->next = curr2->next;
            curr2->next = temp;
        } else {
            curr2 = curr2->next;
        }
    }
}
list 1
list 2

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.