C# solution with stacks


  • 0
    B
    public class Solution {
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            Stack<int> stack1 = new Stack<int>();
            Stack<int> stack2 = new Stack<int>();
            ListNode resultNode = null;
            ListNode node = l1;
            
            while(l1 != null) {
                stack1.Push(l1.val);
                l1 = l1.next;
            }
            
            node = l2;
            
            while(l2 != null) {
                stack2.Push(l2.val);
                l2 = l2.next;
            }
            
            int carry = 0;
    
            while(stack1.Count > 0 || stack2.Count > 0) {
                int num1 = 0;
                int num2 = 0;
                
                if(stack1.Count > 0) {
                    num1 = stack1.Pop();
                }
                
                if(stack2.Count > 0) {
                    num2 = stack2.Pop();
                }
                
                int result = num1 + num2 + carry;
                ListNode head = new ListNode(result % 10);
                
                if(result > 9) {
                    carry = 1;
                }
                else {
                    carry = 0;
                }
                
                head.next = resultNode;
                resultNode = head;
            }
            
            // Account for remaining carry-over value
            if(carry == 1) {
                node = new ListNode(1);
                node.next = resultNode;
                resultNode = node;
            }
            
            return resultNode;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.