C# accepted solution using Stack


  • 0
    R
            public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
    		if(l1==null || l2 == null) 
    			throw new ArgumentNullException("list can't be null");
    		
    		var s1 = PushNodesToStack(l1);
    		var s2 = PushNodesToStack(l2);
    		int carry = 0;
    		ListNode result = null;
    		while (s1.Any() && s2.Any())
    		{
    			int sum = s1.Pop().val+s2.Pop().val+carry;
    			AddSumToResult(ref result, sum, ref carry);
    		}
    
    		while (s1.Any())
    		{
    			int sum = s1.Pop().val + carry;
    			AddSumToResult(ref result, sum, ref carry);
    		}
    
    		while (s2.Any())
    		{
    			int sum = s2.Pop().val + carry;
    			AddSumToResult(ref result, sum, ref carry);
    		}
    
    		while (carry!=0)
    		{
    			int sum = carry;
    			AddSumToResult(ref result, sum, ref carry);
    		}
    		return result;
    	}
    	
    	private static void AddSumToResult(ref ListNode result, int sum, ref int carry)
    	{
    		carry = sum / 10;
    		sum = sum % 10;
    		var temp = new ListNode(sum);
    		temp.next = result;
    		result = temp;
    	}
    
    	private static Stack<ListNode> PushNodesToStack(ListNode head)
    	{
    		Stack<ListNode> result = new Stack<ListNode>();
    		while (head != null)
    		{
    			ListNode temp = head;
    			head = head.next;
    			temp.next = null;
    			result.Push(temp);
    		}
    		return result;
    	}

Log in to reply
 

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