力扣题库2_两数相加
还是通过遍历两个链表的每个节点值,添加到新节点。通过新建中间链表的形式
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode result = new ListNode();
        ListNode nextNode;
        nextNode = result;
        int d = 0;
        while (l1 != null || l2 != null) {
            ListNode node = new ListNode();
            nextNode.next = node;
            int a = 0, b = 0;
            if (l1 != null) {
                a = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                b = l2.val;
                l2 = l2.next;
            }
            int c = a + b + d;
            if (c >= 10) {
                c = c - 10;
                d = 1;
                node.val = c;
            } else {
                d = 0;
                node.val = c;
            }
            nextNode = nextNode.next;
        }
        if (d == 1) {
            ListNode e = new ListNode(1);
            nextNode.next = e;
        }
        return result.next;
    }

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号