두 목록을 하나의 정렬 된 목록으로 병합한다.
목록은 처음 두 목록의 노드를 함께 연결하여 만들어야 한다.
병합된 연결 목록의 헤드를 반환한다.
예시1
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
예시2
Input: list1 = [], list2 = []
Output: []
예시3
Input: list1 = [], list2 = [0]
Output: [0]
제약조건🔎
두 목록의 노드 수는 범위 내에 있습니다.[0, 50]
-100 <= Node.val <= 100
둘 다 내림차순이 아닌 순서로 정렬됩니다.
풀이
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode merge = new ListNode();
ListNode curr = merge;
if(list1 == null) return list2;
if(list2 == null) return list1;
if(list1 == null && list2 == null) return null;
while (list1 != null && list2 != null) {
if(list1.val <= list2.val ) {
curr.next = list1;
list1 = list1.next;
} else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
if(list1 == null) curr.next = list2;
if(list2 == null) curr.next = list1;
return merge.next;
}
}
merge의 첫 번째 노드(헤드)가 0이므로 next값으로 병합된 노드의 헤드의 next를 반환한다.