Clean Java Soultion


  • 0
    A
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	l1 = reverse(l1);
    	l2 = reverse(l2);
    	int c = 0;
    	ListNode head = null;
    	ListNode tail = null;
    
    	while (l1 != null || l2 != null || c != 0) {
    		int a = (l1 == null) ? 0 : l1.val;
    		int b = (l2 == null) ? 0 : l2.val;
    		ListNode node = new ListNode((a + b + c) % 10);
    		c = (a + b + c) / 10;
    
    		if (head == null) {
    			head = node;
    			tail = node;
    		} else {
    			tail.next = node;
    			tail = node;
    		}
    
    		if (l1 != null)
    			l1 = l1.next;
    		if (l2 != null)
    			l2 = l2.next;
    	}
    	return reverse(head);
    }
    
    public ListNode reverse(ListNode head) {
    	ListNode prev = null;
    	while (head != null) {
    		ListNode next = head.next;
    		head.next = prev;
    		prev = head;
    		head = next;
    	}
    	return prev;
    }

Log in to reply
 

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