标签:ext put exce cep red rip ott blog turn
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public int val; 5 * public ListNode next; 6 * public ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { 11 ListNode ret = null; 12 ListNode curNode = null; 13 int advance = 0; 14 15 while (l1 != null || l2 != null) 16 { 17 int cur = advance; 18 19 if (l1 != null) 20 { 21 cur += l1.val; 22 l1 = l1.next; 23 } 24 25 if (l2 != null) 26 { 27 cur += l2.val; 28 l2 = l2.next; 29 } 30 31 if (ret == null) 32 { 33 ret = new ListNode(cur % 10); 34 curNode = ret; 35 } 36 else 37 { 38 curNode.next = new ListNode(cur % 10); 39 curNode = curNode.next; 40 } 41 42 advance = cur / 10; 43 } 44 45 if (advance != 0) curNode.next = new ListNode(advance); 46 47 return ret; 48 } 49 }
标签:ext put exce cep red rip ott blog turn
原文地址:http://www.cnblogs.com/liangmou/p/7782953.html