| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | using LeetCode.Core.Models; |
| | | 13 | | |
| | | 14 | | namespace LeetCode.Algorithms.MergeTwoSortedLists; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class MergeTwoSortedListsLinear : IMergeTwoSortedLists |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n + m) |
| | | 21 | | /// Space complexity - O(1) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="list1"></param> |
| | | 24 | | /// <param name="list2"></param> |
| | | 25 | | /// <returns></returns> |
| | | 26 | | public ListNode? MergeTwoLists(ListNode? list1, ListNode? list2) |
| | 5 | 27 | | { |
| | 5 | 28 | | if (list1 == null) |
| | 2 | 29 | | { |
| | 2 | 30 | | return list2; |
| | | 31 | | } |
| | | 32 | | |
| | 3 | 33 | | if (list2 == null) |
| | 1 | 34 | | { |
| | 1 | 35 | | return list1; |
| | | 36 | | } |
| | | 37 | | |
| | 2 | 38 | | ListNode dummyHead = new(); |
| | 2 | 39 | | var current = dummyHead; |
| | | 40 | | |
| | 9 | 41 | | while (list1 != null && list2 != null) |
| | 7 | 42 | | { |
| | 7 | 43 | | if (list1.val < list2.val) |
| | 4 | 44 | | { |
| | 4 | 45 | | current.next = list1; |
| | 4 | 46 | | list1 = list1.next; |
| | 4 | 47 | | } |
| | | 48 | | else |
| | 3 | 49 | | { |
| | 3 | 50 | | current.next = list2; |
| | 3 | 51 | | list2 = list2.next; |
| | 3 | 52 | | } |
| | | 53 | | |
| | 7 | 54 | | current = current.next; |
| | 7 | 55 | | } |
| | | 56 | | |
| | 2 | 57 | | current.next = list1 ?? list2; |
| | | 58 | | |
| | 2 | 59 | | return dummyHead.next; |
| | 5 | 60 | | } |
| | | 61 | | } |