/*
T2:两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807*/
/**
* Definition for singly-linked list.
*/
1 class ListNode2 {
2
3 int val;
4 ListNode2 next;
5
6 ListNode2(int x) {
7 val = x;
8 }
9 }
/*
时间复杂度O( max(n,m) ) n,m代表链表长度.
思路: 其实就是模拟加法运算,只不过顺序与原来相反而已.
分别遍历2个链表
1.如果两个结点都不为空,就求出他们的和,如果他们的和大于10,就-10,存入当前值,然后让后面的数的和+1
2.如果有一个结点为空,可以吧空结点中的值当成0
3.如果2个结点都为空,说明遍历已经完毕,如果此时还有一位数未加入,如8+9=16,当前位只加入了6,但2个链表都已经
遍历完毕,这时应该再新分配一个结点保存当前的1.
第一个是自己写的代码,第二个是leetcode的代码,思路差不多,但是leetcode代码明显简洁许多.
*/
1 class Solution2 {
2
3 public ListNode2 addTwoNumbers(ListNode2 l1, ListNode2 l2) {
4 if (l1 == null) {
5 return l2;
6 }
7 if (l2 == null) {
8 return l1;
9 }
10
11 ListNode2 list1 = l1;
12 ListNode2 list2 = l2;
13 ListNode2 dummyHead = new ListNode2(0);
14 ListNode2 curr = dummyHead;
15
16 int isGreatThan10 = 0;
17 while (list1 != null || list2 != null) {
18 if (list1 == null || list2 == null) {
19 ListNode2 notEmptyNode = (list1 == null ? list2 : list1);
20 if (isGreatThan10 == 1) {
21 isGreatThan10 = 0;
22 ++notEmptyNode.val;
23 if (notEmptyNode.val == 10) {
24 notEmptyNode.val = 0;
25 isGreatThan10 = 1;
26 }
27 }
28 curr.next = notEmptyNode;
29 curr = curr.next;
30 if (list1 != null) {
31 list1 = list1.next;
32 } else {
33 list2 = list2.next;
34 }
35 } else {
36 int sum = list1.val + list2.val + isGreatThan10;
37 isGreatThan10 = sum >= 10 ? 1 : 0;
38 curr.next = new ListNode2(isGreatThan10 == 1 ? sum - 10 : sum);
39 list1 = list1.next;
40 list2 = list2.next;
41 curr = curr.next;
42 }
43 }
44 if (isGreatThan10 == 1) {
45 curr.next = new ListNode2(1);
46 }
47 return dummyHead.next;
48 }
49 }
1 class Solution2_1 {
2
3 public ListNode2 addTwoNumbers(ListNode2 l1, ListNode2 l2) {
4 if (l1 == null) {
5 return l2;
6 }
7 if (l2 == null) {
8 return l1;
9 }
10 ListNode2 dummyHead = new ListNode2(0);
11 ListNode2 curr = dummyHead;
12 int val1 = 0;
13 int val2 = 0;
14 int add = 0;
15
16 while (l1 != null || l2 != null) {
17 val1 = l1 == null ? 0 : l1.val;
18 val2 = l2 == null ? 0 : l2.val;
19 int sum = val1 + val2 + add;
20 curr.next = new ListNode2(sum % 10);
21 add = sum / 10;
22 curr = curr.next;
23 l1 = l1 == null ? null : l1.next;
24 l2 = l2 == null ? null : l2.next;
25 }
26 if (add > 0) {
27 curr.next = new ListNode2(add);
28 }
29 return dummyHead.next;
30 }
31 }