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.
list1, list2)list1, list2의 node들을 하나의 linked list로 정렬하고 head node를 반환list1, list2가 모두 null에 도달할 때까지 반복
list1, list2 중 작은 node를 선택주의 사항
null이 자주 등장할 수 있으므로 NullPointerException에 주의하자class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = getSmaller(list1, list2);
if (head == null) { // list1, list2 둘 다 null 인 경우
return null;
}
if (head == list1) {
list1 = list1.next;
} else {
list2 = list2.next;
}
ListNode current = head;
while (list1 != null || list2 != null) {
ListNode smallNode = getSmaller(list1, list2);
current.next = smallNode;
current = smallNode;
if (current == list1) {
list1 = list1.next;
} else {
list2 = list2.next;
}
}
return head;
}
private ListNode getSmaller(ListNode node1, ListNode node2) {
if (node1 == null) {
return node2;
}
if (node2 == null) {
return node1;
}
return node1.val <= node2.val ? node1 : node2;
}
}
/**
* 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; }
* }
*/

public class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 != null && list2 != null) {
if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
if (list1 == null) {return list2;}
return list1;
}
}
