You have both numbers represented by a linked list, where each node contains a single digit. reversethe digits is stored in order, such the 1 's digit is at the head of the list. Write a function that adds the numbers and returns the sum as a linked list.
Example
Given 7->1->6 + 5->9->2 . That's, 617 + 295 .
Return 2->1->9 . That's 912 .
Given 3->1->5 5->9->2 and, return 8->0->8 .
There's not much to say about this question, and it's about the same as putting two binary numbers together.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {* val = x; * next = NULL; * } * } */ Public classSolution {/** * @paraml1:the First list *@paraml2:the Second list *@return: The sum list of L1 and L2*/ PublicListNode addlists (listnode L1, ListNode L2) {//Write your code here if(L1 = =NULL) returnL2; if(L2 = =NULL) returnL1; ListNode Fakehead=NewListNode (0); ListNode P=Fakehead; ListNode P1=L1; ListNode P2=L2; intCarry = 0; while(P1! =NULL|| P2! =NULL){ intNUM1 = 0; intnum2 = 0; if(P1! =NULL) {NUM1=P1.val; P1=P1.next; } if(P2! =NULL) {num2=P2.val; P2=P2.next; } P.next=NewListNode ((NUM1 + num2 + carry)% 10); P=P.next; Carry= (NUM1 + num2 + carry)/10; } if(Carry = = 1) {P.next=NewListNode (1); P=P.next; } returnFakehead.next; }}
Lintcode-easy-add numbers