[LeetCode] Add Two Numbers

本文详细阐述了链表相加算法的核心思想、代码实现及其时间复杂度分析,包括如何处理不同长度的链表和进位问题。

The idea is to add the two numbers (represented by linked lists) nodes after nodes and store the result in the longer list. Since we may append the additioanl carry bit after the longer list, we need to be careful not to reach the NULL pointer of the longer list.

The code is as follows. In fact, it is of time O(length(l1) + length(l2)) (the two calls oflistLength) and includes two-pass, but it is very fast in the OJ :-)

The code is as follows, about 20 lines. You may run it on the following examples and then you will understand the details of the code.

 1 class Solution {
 2 public:
 3     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
 4         if (listLength(l1) < listLength(l2))
 5             return addTwoNumbers(l2, l1);
 6         ListNode *r1 = l1, *r2 = l2;
 7         int c = 0;
 8         bool isEnd = false;
 9         while (r2) {
10             int val = r1 -> val + r2 -> val + c;
11             r1 -> val = val % 10;
12             c = val / 10;
13             if (r1 -> next) r1 = r1 -> next;
14             else isEnd = true;
15             r2 = r2 -> next;
16         }
17         while (c) {
18             int val = isEnd ? c : r1 -> val + c;
19             if (isEnd) r1 -> next = new ListNode(val % 10);
20             else r1 -> val = val % 10;
21             c = val / 10;
22             if (r1 -> next) r1 = r1 -> next;
23             else isEnd = true;
24         }
25         return l1;
26     }
27 private:
28     int listLength(ListNode* head) {
29         return head ? 1 + listLength(head -> next) : 0;
30     }
31 };

Examples:

  1. l1 = 5 -> NULL, l2 = 5 -> NULL;
  2. l1 = 1 -> NULL, l2 = 9 -> 9 -> NULL;
  3. l1 = 8 -> 9 -> NULL, l2 = 1 - >NULL.

Well, you guess what? Yeah, these are just the test cases which my code gives mistake before the debugging :-)

转载于:https://www.cnblogs.com/jcliBlogger/p/4732463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值