这个比较简单,掌握好循环条件以及进位条件。

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p = l1;
        ListNode q = l2;
        int ret = 0;
        ListNode prev = null;
        ListNode head = null;
        while(p != null || q != null) {
            int x = ret;
            if (p != null) {
                x = x + p.val;
                p = p.next;
            }
            
            if (q != null) {
                x = x + q.val;
                q = q.next;
            }
            
            if (x >= 10) {
                x = x - 10;
                ret = 1;
            } else {
                ret = 0;
            }
            
            ListNode newNode = new ListNode(x);
            newNode.next = null;
            if (prev == null) {
                prev = newNode;
                head = newNode;
            } else {
                prev.next = newNode;
                prev = newNode;
            }
        }
        
        if (ret > 0) {
            ListNode newNode = new ListNode(ret);
            newNode.next = null;
            prev.next = newNode;
            prev = newNode;
        }
        
        return head;
    }
}

chenatu
106 声望12 粉丝