`

LeetCode 2 - Add Two Numbers

 
阅读更多

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int carry = 0;
    ListNode dummy = new ListNode(0);
    ListNode node = dummy;
    while(l1 != null || l2 != null) {
        int v1 = 0, v2 = 0;
        if(l1!=null) {
            v1 = l1.val;
            l1 = l1.next;
        }
        if(l2!=null) {
            v2 = l2.val;
            l2 = l2.next;
        }
        int sum = carry+v1+v2;
        carry = sum / 10;
        node.next = new ListNode(sum%10);
        node = node.next;
    }
    if(carry != 0) {
        node.next = new ListNode(carry);
    }
    return dummy.next;
}

 

但是如果高位存在链表头部,低为存在链表尾部,该怎么办呢?

两种办法。

方法1:将两个链表反转,用上面方法加和,然后再把结果反转一下就可以了。

方法2:计算出两个链表的长度,假设链表l1的长度为len1,链表l2的长度为len2,且len1>=len2。递归的加低位的数字。

private int carry;
public ListNode addNumber(ListNode l1, ListNode l2) {
	carry = 0;
	int len1 = length(l1), len2 = length(l2);
	ListNode node;
	if(len1 > len2) {
		node = addNumber(l1, l2, len1, len2);
	} else {
		node = addNumber(l2, l1, len2, len1);
	}
	if(carry == 0) return node;
	ListNode head = new ListNode(carry);
	head.next = node;
	return head;
}

private ListNode addNumber(ListNode l1, ListNode l2, int len1, int len2) {
	if(l1 == null) return null;
	ListNode next = addNumber(l1.next, len1 == len2 ? l2.next : l2, 
							  len1-1, len1 == len2 ? len2-1 : len2);
	int sum = l1.val+carry;
	if(len1==len2) {
		sum += l2.val;
		len2--;
	} 
	len1--;
	carry = sum / 10;
	ListNode head = new ListNode(sum%10);
	head.next = next;
	return head;
}

private int length(ListNode head) {
	int len = 0;
	while(head != null) {
		len++;
		head = head.next;
	}
	return len;
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics