LeetCode 2 - Add Two Numbers

原题如下:

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

题目比较简单,需要注意边界情况的处理和链表指针的使用,代码如下:

复制代码
 1 class ListNode {
 2     int val;
 3     ListNode next;
 4 
 5     ListNode(int x) {
 6         val = x;
 7         next = null;
 8     }
 9 }
10 
11 public class AddTwoNumbers2 {
12     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
13         ListNode head = null;
14         ListNode ll1 = l1;
15         ListNode ll2 = l2;
16         int res = 0;
17         ListNode cur = null;
18         while (true) {
19             int curval = 0;
20             curval += res;
21             if (ll1 == null && ll2 == null) {
22                 if (curval != 0) {
23                     cur.next = new ListNode(curval);
24                 }
25                 break;
26             }
27             if (ll1 != null) {
28                 curval += ll1.val;
29                 ll1 = ll1.next;
30             }
31             if (ll2 != null) {
32                 curval += ll2.val;
33                 ll2 = ll2.next;
34             }
35             if (curval >= 10) {
36                 res = 1;
37                 curval -= 10;
38             } else {
39                 res = 0;
40             }
41             if (cur == null) {
42                 head = cur = new ListNode(curval);
43             } else {
44                 cur.next = new ListNode(curval);
45                 cur = cur.next;
46             }
47         }
48         return head;
49     }
50 }
复制代码

参考源码:https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/L2_AddTwoNumbers.java

posted @   pkufork  阅读(213)  评论(0编辑  收藏  举报
编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· AI Agent爆火后,MCP协议为什么如此重要!
· dotnet 源代码生成器分析器入门
· Draw.io:你可能不知道的「白嫖级」图表绘制神器
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始:基于 PyTorch 的图像分类模型
点击右上角即可分享
微信分享提示