https://leetcode.com/problems/merge-two-sorted-lists/description/
두 개의 Linked List를 순서대로 합치는 것 같은데, 간단하겠다.
보통 이런 문제는 while문 세 개 써서 돌리는데,
1번 while 루프 조건이 안되서 탈출했다면 2번이나 3번은 둘 중 하나만 수행할테니
2번이나 3번은 그냥 있는 그대로 리스트에 이어 붙이곤 한다.
이 문제의 경우 Linked List이기 때문에 별도 리스트에 요소 넣는건 신경쓰지 말고
마지막에 남아있는 놈의 포인터를 current에 이어 붙이기만 하면 된다.
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode head = new ListNode();
ListNode current = head;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
current.next = list1;
list1 = list1.next;
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next;
}
if (list1 != null) {
current.next = list1;
} else {
current.next = list2;
}
return head.next;
}
}
재귀로 풀 수도 있다.
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
}