【力扣题目】两数相加(链表)
https://leetcode.cn/problems/add-two-numbers/
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 14 ListNode root = new ListNode(); // 返回值 15 ListNode cursor = root; // 游标 16 int carry = 0; // 进位 17 18 while(l1 != null || l2 != null || carry != 0){ 19 20 // 循环计算节点位(节点1+节点2—— 进位) 21 int sumVal = (l1 != null ? l1.val : 0 ) + (l2 != null ? l2.val : 0) + carry; 22 carry = sumVal /10; 23 // 添加新结点,并下移两个结点 24 ListNode sumNode = new ListNode(sumVal%10); 25 cursor.next = sumNode; 26 cursor = cursor.next; 27 28 29 l1 = (l1 != null ? l1.next:l1); 30 l2 = (l2 != null? l2.next : l2); 31 } 32 return root.next; 33 } 34 }
有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。