LeetCode-Add Two Numbers
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 Hide Tags Linked List Math
这道题在原理上很简单,模拟了加法的运算。但如何使code写的简洁是个难点,另外运用到了前置节点和遍历节点的技术。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 14 if(l1==null && l2 == null){ 15 return null; 16 } 17 else if(l1 != null && l2 == null){ 18 return l1; 19 } 20 else if(l2 != null && l2 == null){ 21 return l2; 22 } 23 24 ListNode dummy = new ListNode(-1); 25 ListNode end = dummy; 26 int carry =0; 27 while(l1 != null || l2 != null || carry !=0){ 28 int current =0; 29 if(l1 != null){ 30 current = current + l1.val; 31 l1 = l1.next; 32 } 33 if(l2 != null){ 34 current = current +l2.val; 35 l2 = l2.next; 36 } 37 if(carry !=0 ){ 38 current = current + carry; 39 } 40 41 end.next = new ListNode(current%10); 42 carry = current / 10; 43 end = end.next; 44 } 45 return dummy.next; 46 47 } 48 }
二刷:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; ListNode dummy = new ListNode(-1); ListNode cur = dummy; while(l1 != null || l2 != null){ int sum = 0; if(l1 == null){ sum = l2.val + carry; l2 = l2.next; } else if(l2 == null){ sum = l1.val + carry; l1 = l1.next; } else{ sum = l1.val + l2.val + carry; l1 = l1.next; l2 = l2.next; } if(sum >= 10){ carry = 1; sum = sum -10; } else{ carry = 0; } ListNode temp = new ListNode(sum); cur.next = temp; cur = temp; } if(carry == 1){ ListNode temp = new ListNode(carry); cur.next = temp; } return dummy.next; } }
posted on 2015-04-17 04:37 IncredibleThings 阅读(150) 评论(0) 编辑 收藏 举报