Practice #4
Coddy의 연결 리스트 - 자료구조 시리즈 #5 코스 레슨 — 14개 중 13번째.
챌린지
쉬움두 개의 정렬된 정수 배열 a와 b(두 개의 정렬된 연결 리스트의 값들)가 주어졌을 때, 두 입력의 모든 값을 포함하는 하나의 정렬된 배열을 반환하는 mergeSorted 함수를 작성하세요.
이 문제를 해결하기 위해 연결 리스트를 사용하세요! 두 리스트를 동시에 탐색하면서, 더 작은 값을 가진 헤드를 반복적으로 결과에 추가하세요.
반드시 LinkedList 클래스를 사용해야 합니다 (node.<ext>와 함께 linkedlist.<ext>에 제공됨). 결과를 계산하기 위해 배열의 내장 reverse, slicing 또는 표준 라이브러리의 리스트 연산과 같은 언어 내장 기능을 사용하지 마세요.
직접 해보기
#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;
}