File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * class ListNode {
4+ * val: number
5+ * next: ListNode | null
6+ * constructor(val?: number, next?: ListNode | null) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.next = (next===undefined ? null : next)
9+ * }
10+ * }
11+ */
12+
13+ /*
14+ 새 mergeList를 만들고 list1, list2를 순회하며 더 작은 값을 mergeList에 넣는다.
15+ 두 리스트의 next가 비게 되면 mergeList의 head를 리턴한다.
16+
17+ 시간복잡도 : O(N+K) (N은 list1의 길이, K는 list2의 길이)
18+
19+ */
20+
21+ function mergeTwoLists (
22+ list1 : ListNode | null ,
23+ list2 : ListNode | null ,
24+ ) : ListNode | null {
25+ let now = null
26+ let head = null
27+
28+ while ( list1 || list2 ) {
29+ if ( ! list2 || ( list1 && list1 . val <= list2 . val ) ) {
30+ if ( ! now ) {
31+ now = list1
32+ head = now
33+ } else {
34+ now . next = list1
35+ now = now . next
36+ }
37+ list1 = list1 . next
38+ } else {
39+ if ( ! now ) {
40+ now = list2
41+ head = now
42+ } else {
43+ now . next = list2
44+ now = now . next
45+ }
46+ list2 = list2 . next
47+ }
48+ }
49+
50+ return head
51+ }
You can’t perform that action at this time.
0 commit comments