Java Recursive Solution without Using Stack


  • 0
    public class Solution {
    	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    		ListNode runner1 = l1;
    		ListNode runner2 = l2;
    
    		while (runner1 != null && runner2 != null) {
    			runner1 = runner1.next;
    			runner2 = runner2.next;
    		}
    
    		ListNode node1 = l1;
    		ListNode node2 = l2;
    		ListNode res = new ListNode(0);
    		ListNode resRunner = res;
    		if (runner1 == null && runner2 != null) {
    			while (runner2 != null) {
    				runner2 = runner2.next;
    				resRunner.next = new ListNode(node2.val);
    				resRunner = resRunner.next;
    				node2 = node2.next;
    			}
    		} else if (runner1 != null && runner2 == null){
    			while (runner1 != null) {
    				runner1 = runner1.next;
    				resRunner.next = new ListNode(node1.val);
    				resRunner = resRunner.next;
    				node1 = node1.next;
    			}
    		}
    
    		while (node1 != null && node2 != null) {
    			resRunner.next = new ListNode(node1.val + node2.val);
    			node1 = node1.next;
    			node2 = node2.next;
    			resRunner = resRunner.next;
    		}
    		resultHelper(res);
    		if (res.val == 0 && res.next != null) {
    			return res.next;
    		} else {
    			return res;
    		}
    	}
    
    	public int resultHelper(ListNode node) {
    		if (node == null) {
    			return 0;
    		}
    		int val = node.val + resultHelper(node.next);
    		node.val = val % 10;
    		return val /10;
    	}
    }
    

Log in to reply
 

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