Add Two Numbers II, clear Java solution


  • 0
    P

    I use the stack to solve this question. Here is my clear code in java:

    	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    		ListNode curr1 = l1, curr2 = l2;
    		Stack<Integer> s1 = new Stack<>();
    		Stack<Integer> s2 = new Stack<>();
    		Stack<Integer> result = new Stack<>();
    		// store the elements of l1 into s1
    		while(curr1 != null){
    			s1.push(curr1.val);
    			curr1 = curr1.next;
    		}
    		// store the elements of l2 into s2
    		while(curr2 != null){
    			s2.push(curr2.val);
    			curr2 = curr2.next;
    		}
    		// store the carry
    		int carry = 0;
    		// plus 
    		while(!s1.isEmpty() || !s2.isEmpty()){
    			int from1 = s1.isEmpty()?0:s1.pop(); 
    			int from2 = s2.isEmpty()?0:s2.pop();
    			int sum = from1 + from2 + carry;
    			result.push(sum % 10); // store the result of each step
    			carry = sum/10; // fix the carry
    		}
    		// important: if the carry > 0, need to add the carry to the result
    		if(carry > 0)
    			result.push(1);
    		
    		ListNode dump = new ListNode(0);
    		ListNode head = dump;
    		// generate the ListNode according to the result stack
    		while(!result.isEmpty()){
    			head.next = new ListNode(result.pop());
    			head = head.next;
    		}
    		return dump.next;
    	}
    

Log in to reply
 

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