https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode-solution/
- 总思路: 同时遍历两个链表,对应数字相加, 然后需要把头节点抓住,最后返回
细节:
用一个变量carry来表示进位,若为1表示有进位,若为0无进位,
在相加的时候把carry一起加进去,
sum % 10 就是新节点的值
sum / 10 就是下一次的carry值到最后的时候可能会有进位,别忘了检查
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {if (l1 == null) return l2;if (l2 == null) return l1;ListNode head = new ListNode(0);ListNode last = head;int carry = 0;while (l1 != null || l2 != null) {int v1 = 0;if (l1 != null) {v1 = l1.val;l1 = l1.next;}int v2 = 0;if (l2 != null) {v2 = l2.val;l2 = l2.next;}int sum = v1 + v2 + carry;carry = sum / 10;last.next = new ListNode(sum % 10);last = last.next;}if (carry > 0) {last.next = new ListNode(carry);}return head.next;}
