Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
두개의 정렬된 연결 리스트를 합치고, 이를 정렬된 리스트로 반환해라. 이 리스트는 처음 2개의 리스트의 노드들을 함께 잘라이어 만들어라.
Example 1:

Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both l1 and l2 are sorted in non-decreasing order.
제약사항 :
모든 리스트의 노드의 수는 0, 50 사이
-100 <= 노드.값 <= 100
l1, l2 모두 non-decreasing order(-> 증가) 로 정렬됨.
생각하기
1. 둘 중 작은 값을 현재 노드에 저장
2. 둘 중 하나만 null 인 경우에 대한 처리
3. 0값이 안나오도록 다음값부터 return
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result_node = new ListNode();
// 내가 지정한 값이 head로
ListNode curr_node = result_node;
while(l1 != null && l2 != null) {
if(l1.val < l2.val ) {
curr_node.next = l1;
l1 = l1.next;
} else {
curr_node.next = l2;
l2 = l2.next;
}
// 노드가 위의 과정을 끝낸 현재와 같도록
curr_node = curr_node.next;
}
// 둘 중 하나가 null이 되어도 다른 하나가 끝날 때 까지 실행
// l1이 null이면 l2를 저장
if(l1 == null) {
curr_node.next = l2;
}
// l2가 null이면 l1을 저장
if(l2 == null) {
curr_node.next = l1;
}
return result_node.next;
}
}'Edu. > Leetcode' 카테고리의 다른 글
| 112. Path Sum (0) | 2021.08.02 |
|---|---|
| 13. Roman to Integer (0) | 2021.07.29 |