题目传送门
方法一:迭代
文字描述看代母注释
class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {//定义头结点和当前节点ListNode head = null,cur = null;//carry记录进位情况。int carry = 0; while(l1 != null || l2 != null){//判断节点是否为null。如果不为null则赋值int n1 = l1 != null ? l1.val : 0;int n2 = l2 != null ? l2.val : 0;//计算两个节点的和。并且若有进位,加上进位。int sum = n1 + n2 + carry;//如果头节点为空,则新建节点if(head == null){head = cur = new ListNode(sum%10);}else{ //不为空则新添节点cur.next = new ListNode(sum%10);cur = cur.next;}//计算进位的值carry = sum /10;//不为null则向后移动if(l1 != null){l1 = l1.next;}if(l2 != null){l2 = l2.next;}}//最后若有进位。则新添进位值的节点。if(carry > 0){cur.next = new ListNode(carry);}return head;}
}