| | | 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.DoubleNumberRepresentedAsLinkedList; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class DoubleNumberRepresentedAsLinkedListStack : IDoubleNumberRepresentedAsLinkedList |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n) |
| | | 21 | | /// Space complexity - O(n) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="head"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public ListNode? DoubleIt(ListNode? head) |
| | 2 | 26 | | { |
| | 2 | 27 | | var stack = new Stack<ListNode>(); |
| | | 28 | | |
| | 8 | 29 | | while (head != null) |
| | 6 | 30 | | { |
| | 6 | 31 | | stack.Push(head); |
| | | 32 | | |
| | 6 | 33 | | head = head.next; |
| | 6 | 34 | | } |
| | | 35 | | |
| | 2 | 36 | | var dummyHead = new ListNode(); |
| | | 37 | | |
| | 2 | 38 | | var carry = 0; |
| | | 39 | | |
| | 8 | 40 | | while (stack.Count > 0) |
| | 6 | 41 | | { |
| | 6 | 42 | | var current = stack.Pop(); |
| | | 43 | | |
| | 6 | 44 | | var newVal = (current.val * 2) + carry; |
| | | 45 | | |
| | 6 | 46 | | if (newVal > 9) |
| | 5 | 47 | | { |
| | 5 | 48 | | carry = 1; |
| | | 49 | | |
| | 5 | 50 | | newVal %= 10; |
| | 5 | 51 | | } |
| | | 52 | | else |
| | 1 | 53 | | { |
| | 1 | 54 | | carry = 0; |
| | 1 | 55 | | } |
| | | 56 | | |
| | 6 | 57 | | current.val = newVal; |
| | 6 | 58 | | current.next = dummyHead.next; |
| | | 59 | | |
| | 6 | 60 | | dummyHead.next = current; |
| | 6 | 61 | | } |
| | | 62 | | |
| | 2 | 63 | | if (carry > 0) |
| | 1 | 64 | | { |
| | 1 | 65 | | dummyHead.next = new ListNode(1, dummyHead.next); |
| | 1 | 66 | | } |
| | | 67 | | |
| | 2 | 68 | | return dummyHead.next; |
| | 2 | 69 | | } |
| | | 70 | | } |