| | | 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.AddTwoNumbers2; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class AddTwoNumbers2Stack : IAddTwoNumbers2 |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n + m) |
| | | 21 | | /// Space complexity - O(n + m) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="l1"></param> |
| | | 24 | | /// <param name="l2"></param> |
| | | 25 | | /// <returns></returns> |
| | | 26 | | public ListNode AddTwoNumbers(ListNode l1, ListNode l2) |
| | 3 | 27 | | { |
| | 3 | 28 | | var l1Stack = new Stack<int>(); |
| | 3 | 29 | | var l1Node = l1; |
| | | 30 | | |
| | 11 | 31 | | while (l1Node != null) |
| | 8 | 32 | | { |
| | 8 | 33 | | l1Stack.Push(l1Node.val); |
| | | 34 | | |
| | 8 | 35 | | l1Node = l1Node.next; |
| | 8 | 36 | | } |
| | | 37 | | |
| | 3 | 38 | | var l2Stack = new Stack<int>(); |
| | 3 | 39 | | var l2Node = l2; |
| | | 40 | | |
| | 10 | 41 | | while (l2Node != null) |
| | 7 | 42 | | { |
| | 7 | 43 | | l2Stack.Push(l2Node.val); |
| | | 44 | | |
| | 7 | 45 | | l2Node = l2Node.next; |
| | 7 | 46 | | } |
| | | 47 | | |
| | 3 | 48 | | ListNode? resultNode = null; |
| | 3 | 49 | | var remainder = 0; |
| | | 50 | | |
| | 11 | 51 | | while (l1Stack.Count > 0 || l2Stack.Count > 0 || remainder > 0) |
| | 8 | 52 | | { |
| | 8 | 53 | | var node1 = l1Stack.Count > 0 ? l1Stack.Pop() : 0; |
| | 8 | 54 | | var node2 = l2Stack.Count > 0 ? l2Stack.Pop() : 0; |
| | | 55 | | |
| | 8 | 56 | | var value = node1 + node2 + remainder; |
| | | 57 | | |
| | 8 | 58 | | if (value > 9) |
| | 2 | 59 | | { |
| | 2 | 60 | | remainder = 1; |
| | 2 | 61 | | value -= 10; |
| | 2 | 62 | | } |
| | | 63 | | else |
| | 6 | 64 | | { |
| | 6 | 65 | | remainder = 0; |
| | 6 | 66 | | } |
| | | 67 | | |
| | 8 | 68 | | resultNode = new ListNode(value, resultNode); |
| | 8 | 69 | | } |
| | | 70 | | |
| | 3 | 71 | | return resultNode!; |
| | 3 | 72 | | } |
| | | 73 | | } |