标签:
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 }
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4433834.html