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
在码的时候需要注意各个边界问题,考虑到零输入,单输入,单进位的可能性,反复修改,例如:[0][1],[5][5],[1,8][0]
在编程之前要先想好算法以及过程,先谋而后动。
可以用三指针同时进行,代码会简洁很多,不要破坏原有的链表,这是一个很好的习惯。
1 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 int carry =0; 4 5 ListNode newHead = new ListNode(0); 6 ListNode p1 = l1, p2 = l2, p3=newHead; 7 8 while(p1 != null || p2 != null){ 9 if(p1 != null){ 10 carry += p1.val; 11 p1 = p1.next; 12 } 13 14 if(p2 != null){ 15 carry += p2.val; 16 p2 = p2.next; 17 } 18 19 p3.next = new ListNode(carry%10); 20 p3 = p3.next; 21 carry /= 10; 22 } 23 24 if(carry==1) 25 p3.next=new ListNode(1); 26 27 return newHead.next; 28 } 29 }
下面的代码的思路是将为空的链表的值设为0:
1 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 4 ListNode result = new ListNode(0); 5 ListNode start = result; 6 int temp = 0; 7 ListNode t1 = l1; 8 ListNode t2 = l2; 9 int t1v; 10 int t2v; 11 for (; t1 != null || t2 != null;) { 12 result.next = new ListNode(0); 13 result = result.next; 14 if (t1 == null) 15 t1v = 0; 16 else { 17 t1v = t1.val; 18 t1 = t1.next; 19 } 20 if (t2 == null) 21 t2v = 0; 22 else { 23 t2v = t2.val; 24 t2 = t2.next; 25 } 26 result.val = (t1v + t2v + temp) % 10; 27 temp = (t1v + t2v + temp) / 10; 28 29 } 30 if (temp != 0) { 31 result.next = new ListNode(0); 32 result.next.val = temp; 33 } 34 return start.next; 35 36 } 37 }