Menu
Coddy logo textTech

Practice #4

Lesson 13 of 14 in Coddy's Linked List - Data Structures Series #5 course.

challenge icon

Challenge

Easy

Given two sorted integer arrays a and b (the values of two sorted linked lists), write a function mergeSorted that returns a single sorted array containing all values from both inputs.

Use a linked list to solve this problem! Walk both lists in parallel, repeatedly taking the smaller head into your result.

You must use the LinkedList class (provided in linkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' built-in reverse, slicing, or stdlib list operations to compute the result.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"

int main() {
    char line1[8192];
    char line2[8192];
    if (!fgets(line1, sizeof(line1), stdin)) line1[0] = '\0';
    if (!fgets(line2, sizeof(line2), stdin)) line2[0] = '\0';
    int a[4096];
    int alen = 0;
    char* tok = strtok(line1, " \t\r\n");
    while (tok) { a[alen++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    int b[4096];
    int blen = 0;
    tok = strtok(line2, " \t\r\n");
    while (tok) { b[blen++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    int rs = 0;
    int* r = mergeSorted(a, alen, b, blen, &rs);
    for (int idx = 0; idx < rs; idx++) {
        if (idx > 0) printf(" ");
        printf("%d", r[idx]);
    }
    printf("\n");
    return 0;
}

All lessons in Linked List - Data Structures Series #5