LeetCode 2: Add Two Numbers

本文介绍了一种使用链表实现两个数相加的方法。通过遍历两个链表,逐位进行加法运算并考虑进位,最终形成一个新的链表来表示两数之和。文章提供了详细的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tips: Tried to use a private method to simplize the code. But found that object is passed by reference. So even if you have ListNode as l, and l = l.next, it is reference change. It will not impac the object in caller function.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         if (l1 == null) {
12             return l2;
13         }
14         
15         if (l2 == null) {
16             return l1;
17         }
18         ListNode result = new ListNode(0);
19         ListNode tail = result;
20         int c = 0;
21         while (l1 != null || l2 != null) {
22             int n1 = 0;
23             int n2 = 0;
24             if (l1 != null) {
25                 n1 = l1.val;
26                 l1 = l1.next;
27             }
28             
29             if (l2 != null) {
30                 n2 = l2.val;
31                 l2 = l2.next;
32             }
33             tail.next = new ListNode((n1 + n2 + c)%10);
34             tail = tail.next;
35             c = (n1 + n2 + c) / 10;
36         }
37         
38         if (c > 0) {
39             tail.next = new ListNode(c);
40         }
41         
42         return result.next;
43     }
44 }

 

转载于:https://www.cnblogs.com/shuashuashua/p/7233599.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值