Skip to content

Commit 1ab1e6f

Browse files
committed
merge two sorted lists solution
1 parent 9f896bb commit 1ab1e6f

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
ListNode는 파라미터로 current value와 next value를 지닌다.
3+
배열 메서드도 사용할 수 없다.
4+
5+
나는 원초적인 방법으로 해결해보았다.
6+
result 배열에 모든 수를 다 넣고, sort()하는 것이다.
7+
여기서 중요한 점은 '어떻게 배열 → ListNode로 변경하느냐'이다.
8+
[1, 2, 3] 배열을 1 → 2 → 3 리스트 노드를 만들기 위해서는 컴퓨터 구조상 역방향인 3부터 가져와야한다.
9+
이때 사용한 메서드는 'reduceRight()'다.
10+
reduceRight() 메서드는 reduce() 작업순서의 역방향이다.
11+
12+
TC : O(nLogN) → sort()
13+
SC : O(n)
14+
*/
15+
/**
16+
* Definition for singly-linked list.
17+
* function ListNode(val, next) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.next = (next===undefined ? null : next)
20+
* }
21+
*/
22+
/**
23+
* @param {ListNode} list1
24+
* @param {ListNode} list2
25+
* @return {ListNode}
26+
*/
27+
function mergeTwoLists(list1, list2) {
28+
let result = [];
29+
let node1 = list1;
30+
let node2 = list2;
31+
32+
while (node1 !== null) {
33+
result.push(node1.val);
34+
node1 = node1.next;
35+
}
36+
37+
while (node2 !== null) {
38+
result.push(node2.val);
39+
node2 = node2.next;
40+
}
41+
42+
return result
43+
.sort((a, b) => a - b)
44+
.reduceRight((next, val) => new ListNode(val, next), null);
45+
}

0 commit comments

Comments
 (0)