Difficulty: Medium
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/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
2个数据链相加,向后进位,相当于倒置的加法,我们需要一个中间值来存放进位其他的按位相加即可,在这里遇到一个问题,如何在循环中给个temp指针不断的更新然后又让结果能保持在变量中?
定义了一个Loop和Result,2个Node在一开始都指向同一个地址,然后loop又指向loop复制前的loop.next,第一次也是Result.Next的地址,以此类推,每次重定向都是指向下一级result.next,最后返回result.next即可。
然后第一个和第二个的差别中间变量sum,第一个等于计算了2次sum,而第二个只计算了一次,运行时间比第一次上,因此多次利用的值最好先存储起来。
My submission 1: Accepted Runtime:234ms
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode result=new ListNode(0); 3 int carray = 0; 4 ListNode p = l1; 5 ListNode q = l2; 6 ListNode loop = result; 7 while (p != null || q != null) 8 { 9 int a = p != null ? p.val : 0; 10 int b = q != null ? q.val : 0; 11 12 int sum = (a + b + carray)%10; 13 14 //loop.val = sum; 15 //loop = loop.next = new ListNode(0); 16 loop.next = new ListNode(sum); 17 loop = loop.next; 18 19 carray = (a + b + carray) / 10; 20 p = p!=null?p.next:null; 21 q = q!=null?q.next:null; 22 23 } 24 if(carray>0) 25 loop.next=new ListNode(carray); 26 return result.next; 27 }
My submission 2: Accepted Runtime:209ms
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode result=new ListNode(0); 3 int carray = 0; 4 ListNode p = l1; 5 ListNode q = l2; 6 ListNode loop = result; 7 while (p != null || q != null) 8 { 9 int a = p != null ? p.val : 0; 10 int b = q != null ? q.val : 0; 11 12 int sum = a + b + carray; 13 14 //loop.val = sum; 15 //loop = loop.next = new ListNode(0); 16 loop.next = new ListNode(sum%10); 17 loop = loop.next; 18 19 carray = sum / 10; 20 p = p!=null?p.next:null; 21 q = q!=null?q.next:null; 22 23 } 24 if(carray>0) 25 loop.next=new ListNode(carray); 26 return result.next; 27 }
复杂度:循环的终止取决于2个node的node个数中较长的那一个,因此为O(MAX(m,n)),新的node最长为max(m,n)+1 因此空间复杂度为O(max(m,n)).