You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a 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.
https://leetcode.com/problems/merge-two-sorted-lists/
Merge Two Sorted Lists - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
두 LinkedList의 대소관계를 따져 순차적으로 반환하는 문제이다. while을 쓰기전에 재귀로 풀 수 있는지를 따져보면 좀더 수월할 것 같다.
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
if(list1.val > list2.val) {
list2.next = mergeTwoLists(list2.next, list1);
return list2;
} else {
list1.next = mergeTwoLists(list2, list1.next);
return list1;
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 22. Generate Parentheses (0) | 2022.06.30 |
---|---|
LeetCode 160. Intersection of Two Linked Lists (0) | 2022.06.29 |
LeetCode 234. Palindrome Linked List (0) | 2022.06.28 |
LeetCode 206. Reverse Linked List (0) | 2022.06.28 |
LeetCode 543. Diameter of Binary Tree (0) | 2022.06.27 |