#문제 설명
#문제 풀이
#Iterative 풀이
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode handler = head;
while(l1 != null && l2 != null) {
if (l1.val <= l2.val) {
handler.next = l1;
l1 = l1.next;
} else {
handler.next = l2;
l2 = l2.next;
}
handler = handler.next;
}
if (l1 != null) {
handler.next = l1;
} else if (l2 != null) {
handler.next = l2;
}
return head.next;
}
}
#Recursion 풀이
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode handler;
if(l1.val < l2.val) {
handler = l1;
handler.next = mergeTwoLists(l1.next, l2);
} else {
handler = l2;
handler.next = mergeTwoLists(l1, l2.next);
}
return handler;
}
}
//또는
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
'LeetCode > Linked List' 카테고리의 다른 글
[Medium] 142. Linked List Cycle II (0) | 2022.09.02 |
---|---|
[Easy] 141. Linked List Cycle (0) | 2022.08.29 |
[Easy] 206. Reverse Linked List (0) | 2022.08.28 |
[Medium] 2. Add Two Numbers (0) | 2022.08.25 |
[Easy] 234. Palindrome Linked List (0) | 2022.08.24 |