Topic:
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
Exercises
The operation of single-linked list, we should pay attention to the judgment when the list is empty
/** Definition for singly-linked list. * public class ListNode {* int val, * ListNode next; * ListNode (in T x) {* val = x; * next = NULL; *} *}*/ Public classSolution { PublicListNode addtwonumbers (listnode L1, ListNode L2) {if(L1 = =NULL) returnL2; if(L2 = =NULL) returnL1; ListNode result=NewListNode (-1); ListNode node=result; intcarry =0; while(L1! =NULL|| L2! =NULL){ intVal1 = L1 = =NULL?0: L1.val; intVal2 = L2 = =NULL?0: L2.val; Node.next=NewListNode ((Val1 + val2 + carry)%Ten); Carry= Val1 + Val2 + carry >=Ten?1:0; if(L1! =NULL) L1=L1.next; if(L2! =NULL) L2=L2.next; Node=Node.next; } if(Carry = =1) Node.next=NewListNode (1); returnResult.next; }}
Reference:
Http://www.cnblogs.com/springfor/p/3864493.html
2. Add the Numbers