π‘ LeetCode 21 - Merge Two Sorted Lists
π‘ LeetCode 21 - Merge Two Sorted Lists
λ¬Έμ
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
μ μΆλ ₯ μμ
β μμ 1
1
2
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
β μμ 2
1
2
Input: list1 = [], list2 = []
Output: []
β μμ 3
1
2
Input: list1 = [], list2 = [0]
Output: [0]
μ μ½μ‘°κ±΄
- `The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
- Both list1 and list2 are sorted in non-decreasing order.
μμ± μ½λ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// 1. λ³μ μ μΈ λ° μ΄κΈ°ν
ListNode resultNode = new ListNode();
ListNode tempNode = resultNode;
// 2. 리μ€νΈμ κ²°κ³Ό μμλλ‘ μΆκ°
while (list1 != null || list2 != null) {
if (list1 == null) {
tempNode.next = list2;
list2 = list2.next;
} else if (list2 == null) {
tempNode.next = list1;
list1 = list1.next;
} else {
if (list1.val <= list2.val) {
tempNode.next = list1;
list1 = list1.next;
} else {
tempNode.next = list2;
list2 = list2.next;
}
}
tempNode = tempNode.next;
}
// 3. λ°ν
return resultNode.next;
}
}
ListNode
λ λ¬Έμ μμ μ£Όμ΄μ§λ ν΄λμ€λ‘, μ£Όμμ ν΅ν΄ μ΄λ»κ² μμ±λμ΄ μλμ§ μ μ μμλ€.- μ£Όμ΄μ§ νλΌλ―Έν°κ° λ¬Έμ μμ μ£Όμ΄μ§
ListNode
μΈμ€ν΄μ€κ° μλ λ°°μ΄μ΄λList
μλ€λ©΄Deque
λ₯Ό μ¬μ©ν μ μμμ κ² κ°λ€.
νκ³
- μ°Έμ‘° κ°λ
μ μ 리νλ©° λ‘컬 λ³μλ
Stack
λ©λͺ¨λ¦¬μ, μΈμ€ν΄μ€λHeap
λ©λͺ¨λ¦¬μ μμ±λλ€λ μ μ μκ² λμλ€. - μΈμ€ν΄μ€λ λ©μλ μ€ν μ€κ°μ
null
μ μ°Έμ‘°νλλΌλ λ°λ‘ μ¬λΌμ§μ§ μκ³ , λ©μλκ° μ’ λ£λλ©΄ λ©λͺ¨λ¦¬ μμμ μμ΄μ§λ€κ³ νλ€.
This post is licensed under CC BY 4.0 by the author.