File tree 3 files changed +58
-2
lines changed 3 files changed +58
-2
lines changed Original file line number Diff line number Diff line change @@ -39,6 +39,8 @@ public class Linkedlist {
39
39
如果想要删除单链表上的节点, 也非常简单,就是删除过程的逆过程。这里不再赘述。
40
40
41
41
### 拓展
42
+
43
+
42
44
网上链表相关的代码有比较多,这里可以考虑使用链表来实现队列/栈。
43
45
队列:一种先进先出的结构
44
46
栈: 一种先进后出的结构
@@ -212,7 +214,7 @@ void showQuack(Quack qs) {
212
214
}
213
215
```
214
216
215
- 那么我们来编写程序来使用,我们来反转字符串。
217
+ 那么我们来编写程序来使用,我们来反转字符串。反转字符串这里使用了栈.
216
218
revarg.c
217
219
218
220
``` c
@@ -262,4 +264,6 @@ gcc Quack.c revarg.c
262
264
263
265
[Leetcode86 分割链表题解](linkedlist/leetcode86.md)
264
266
265
- [Leetcode 203 移除链表元素题解](linkedlist/leetcode203.md)
267
+ [Leetcode 203 移除链表元素题解](linkedlist/leetcode203.md)
268
+
269
+ [Leetcode 2 两数相加](linkedlist/leetcode2.md)
Original file line number Diff line number Diff line change
1
+ ### 描述
2
+ 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
3
+
4
+ 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
5
+
6
+ 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
7
+
8
+ 示例:
9
+
10
+ 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
11
+ 输出:7 -> 0 -> 8
12
+ 原因:342 + 465 = 807
13
+
14
+ [ 点击此处查看原题] ( https://leetcode-cn.com/problems/add-two-numbers/ )
15
+
16
+ ### 思路
17
+
18
+ 经过那么多的链表专题训练,回来看这个题,其实不难了。
19
+ 我们来仔细分析一下难点和出问题的点在哪里。
20
+ 首先,让我们模拟一下我们手工做加法的时候的情况,每一位相加,如何处理进位?
21
+ 我们想到运算符的 ` % ` 和 ` / ` 这两个运算。
22
+ 当然,我们需要一个哑节点来构造一个新的链表,这有利于我们写代码。
23
+
24
+ 话不多说,丢代码:
25
+ ``` java
26
+ class Solution {
27
+ public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
28
+ // dummy node.
29
+ ListNode dummy = new ListNode (- 1 );
30
+ ListNode p = l1, q = l2, curr = dummy;
31
+ int carry = 0 ;
32
+ while (p != null || q != null ) {
33
+ int x = p != null ? p. val : 0 ;
34
+ int y = q != null ? q. val : 0 ;
35
+ int sum = x + y + carry;
36
+ carry = sum / 10 ; // 这里注意进位上面的处理.
37
+ curr. next = new ListNode (sum % 10 ); // 构造答案
38
+ curr = curr. next;
39
+ if (p != null ) p = p. next;
40
+ if (q != null ) q = q. next;
41
+ }
42
+ if (carry > 0 ) {
43
+ curr. next = new ListNode (carry);
44
+ }
45
+ return dummy. next;
46
+ }
47
+ }
48
+
49
+ ```
Original file line number Diff line number Diff line change @@ -59,4 +59,7 @@ public ListNode reverseList(ListNode head) {
59
59
return p;
60
60
}
61
61
```
62
+ #### 复杂度分析
63
+ - 时间复杂度:__ O(n)__ , n是列表长度。
64
+ - 空间复杂度:__ O(n)__ ,函数的栈帧。
62
65
走到这里,相信对递归有了更深刻的理解。
You can’t perform that action at this time.
0 commit comments