|
| 1 | +# Merge Two Sorted Lists |
| 2 | + |
| 3 | +## Intuition |
| 4 | + |
| 5 | +<!-- Describe your first thoughts on how to solve this problem. --> |
| 6 | + |
| 7 | +## Approach |
| 8 | + |
| 9 | +<!-- Describe your approach to solving the problem. --> |
| 10 | + |
| 11 | +## Complexity |
| 12 | + |
| 13 | +- Time complexity: |
| 14 | +<!-- Add your time complexity here, e.g. $$O(n)$$ --> |
| 15 | + |
| 16 | +- Space complexity: |
| 17 | +<!-- Add your space complexity here, e.g. $$O(n)$$ --> |
| 18 | + |
| 19 | +## Code |
| 20 | + |
| 21 | +``` |
| 22 | +/** |
| 23 | + * Definition for singly-linked list. |
| 24 | + * public class ListNode { |
| 25 | + * int val; |
| 26 | + * ListNode next; |
| 27 | + * ListNode() {} |
| 28 | + * ListNode(int val) { this.val = val; } |
| 29 | + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
| 30 | + * } |
| 31 | + */ |
| 32 | + |
| 33 | +class Solution { |
| 34 | + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { |
| 35 | + ListNode sortedList = new ListNode(); |
| 36 | + if (list1 == null) |
| 37 | + return list2; |
| 38 | + if (list2 == null) |
| 39 | + return list1; |
| 40 | + if (list1.val < list2.val){ |
| 41 | + sortedList = list1; |
| 42 | + list1 = list1.next; |
| 43 | + } else { |
| 44 | + sortedList = list2; |
| 45 | + list2 = list2.next; |
| 46 | + } |
| 47 | + sortedList.next = mergeTwoLists(list1, list2); |
| 48 | + return sortedList; |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
0 commit comments