
난이도: ★★☆☆☆ • solved on: 2025-11-07


SinglyLinkedListNode: 단일 연결 리스트 노드 구조
문제 분해
- 두 리스트를 순회하며 모든 노드의 데이터를 ArrayList에 저장.
- ArrayList를
Collections.sort()로 정렬한 뒤, 새 리스트를 생성.핵심 로직 흐름
head1, head2 순차 탐색 → arr에 추가 Collections.sort(arr) arr 순회하며 새로운 연결 리스트 생성 ``예외 처리
- 두 리스트 중 하나가 null일 경우 → 다른 리스트를 그대로 반환하면 됨.
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
SinglyLinkedListNode head1Current = head1;
SinglyLinkedListNode head2Current = head2;
ArrayList<Integer> arr = new ArrayList<>();
while(head1Current != null){
arr.add(head1Current.data);
head1Current = head1Current.next;
}
while(head2Current != null){
arr.add(head2Current.data);
head2Current = head2Current.next;
}
Collections.sort(arr);
SinglyLinkedListNode result = new SinglyLinkedListNode(arr.get(0));
SinglyLinkedListNode resultCurrent = result;
for(int i = 1; i < arr.size(); i++){
resultCurrent.next = new SinglyLinkedListNode(arr.get(i));
resultCurrent = resultCurrent.next;
}
return result;
}
- 문제 분해
- 이미 정렬된 두 리스트이므로 정렬 과정이 필요 없음.
- 두 리스트의 현재 노드를 비교하며 더 작은 값을 결과 리스트에 추가.
핵심 로직 흐름
while (head1 != null && head2 != null): if (head1.data < head2.data): attach head1 → move head1 else: attach head2 → move head2 남은 노드 전체를 결과 리스트 뒤에 연결예외 처리
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
if (head1 == null) return head2;
if (head2 == null) return head1;
SinglyLinkedListNode mergedHead;
// 초기 head 설정
if (head1.data < head2.data) {
mergedHead = head1;
head1 = head1.next;
} else {
mergedHead = head2;
head2 = head2.next;
}
SinglyLinkedListNode current = mergedHead;
// 병합
while (head1 != null && head2 != null) {
if (head1.data < head2.data) {
current.next = head1;
head1 = head1.next;
} else {
current.next = head2;
head2 = head2.next;
}
current = current.next;
}
// 남은 노드 연결
if (head1 != null) current.next = head1;
if (head2 != null) current.next = head2;
return mergedHead;
}
방법 1 (ArrayList)
- 시간 복잡도: O((N+M) log(N+M))
- 공간 복잡도: O(N+M)
방법 2 (투 포인터)
- 시간 복잡도: O(N+M)
- 공간 복잡도: O(1) (새 노드 생성 없이 기존 노드 연결만 변경)
비슷한 유형 (GPT 추천):
확장 문제 (GPT 추천):