首页 > 其他分享 >【力扣题目】两数相加(链表)

【力扣题目】两数相加(链表)

时间:2023-02-14 23:45:22浏览次数:47  
标签:力扣 ListNode val 相加 next 链表 l2 l1 null

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 }

 

标签:力扣,ListNode,val,相加,next,链表,l2,l1,null
From: https://www.cnblogs.com/luyj00436/p/17121255.html

相关文章