2. Add Two Numbers

没什么特别的。不在原链表上操作,把每一位保存到一个新的链表里面。

程序大概分四段:

1. 当l1和l2都不为空的时候

2. 当l1不为空的时候

3. 当l2不为空的时候

4. 当carry!=0的时候,再建一个新的节点放在末尾

 

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(-1);
        ListNode head = res;
        if(l1 == null || l2 == null) {
            return res.next;
        }
        int carry = 0;
        while(l1 != null && l2 != null) {
            int sum = l1.val + l2.val + carry;
            if(sum >= 10) {
                sum -= 10;
                carry = 1;
            } else {
                carry = 0;
            }
            ListNode nextNode = new ListNode(sum);
            res.next = nextNode;
            res = res.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1 != null) {
            int sum = l1.val + carry;
            if(sum >= 10) {
                sum -= 10;
                carry = 1;
            } else {
                carry = 0;
            }
            ListNode nextNode = new ListNode(sum);
            res.next = nextNode;
            res = res.next;
            l1 = l1.next;
        }
        while(l2 != null) {
            int sum = l2.val + carry;
            if(sum >= 10) {
                sum -= 10;
                carry = 1;
            } else {
                carry = 0;
            }
            ListNode nextNode = new ListNode(sum);
            res.next = nextNode;
            res = res.next;
            l2 = l2.next;
        }
        if(carry != 0) {
            ListNode nextNode = new ListNode(1);
            res.next = nextNode;
        }
        return head.next;
    }

 bug记录:

1.想加的时候,移动了res,但是忘了移动l1和l2

既记得res = res.next, 但是忘了l1 = l1.next, l2 = l2.next

2.最终return的时候是返回head.next不是head

posted @ 2016-01-28 01:04  warmland  阅读(201)  评论(0编辑  收藏  举报