Translation:
给你两个表示两个非负数字的链表。数字以相反的顺序存储,其节点包含单个数字。将这两个数字相加并将其作为一个链表返回。输入: (243) + (564708
Original question:
You are given BothLinked lists representing BothNon-negative numbers. The digits is storedinchReverse order and each ofTheir nodes containaSingle digit. Add the BothNumbers and return it as aLinked list. Input: (2-4-3) + (5-6-4) Output:7-0-8
C++
/** * Definition forsingly-linked list. * struct ListNode {*intVal * ListNode *Next; * ListNode (intx): Val (x),Next(NULL) {} * }; */classSolution { Public: listnode* addtwonumbers (listnode* L1, listnode* L2) {intcarry=0; listnode* listnode=NewListNode (0); listnode* P1=l1,*p2=l2,*p3=listnode; while(p1!=NULL|p2!=NULL) {if(p1!=NULL) {carry+=p1->val; P1=p1->Next; }if(p2!=NULL) {carry+=p2->val; P2=p2->Next; } p3->Next=NewListNode (carry%Ten); P3=p3->Next; Carry/=Ten; }if(carry==1) p3->Next=NewListNode (1); Return listnode->Next; }};
C#
/** * Definition for singly-linked list. * public class ListNode {* public int val, * public ListNode next; public ListNode (int x) {val = x;}} * * Public class solution{ PublicListNodeaddtwonumbers(ListNode L1, ListNode L2) {intcarry =0; ListNode listnode=NewListNode (0); ListNode p1 = L1, p2 = L2, p3 = ListNode; while(P1! =NULL|| P2! =NULL) {if(P1! =NULL) {carry + = P1.val; P1 = P1.next; }if(P2! =NULL) {carry + = P2.val; P2 = p2.next; } P3.next =NewListNode (Carry%Ten); P3 = P3.next; Carry/=Ten; }if(Carry = =1) P3.next =NewListNode (1);returnListnode.next; }}
Java
Public classSolution { PublicListNodeaddtwonumbers(ListNode L1, ListNode L2) {intcarry=0; ListNode listnode=NewListNode (0); ListNode P1=l1,p2=l2,p3=listnode; while(p1!=NULL|| p2!=NULL){if(p1!=NULL) {carry+=p1.val; P1=p1.next; }if(p2!=NULL) {carry+=p2.val; P2=p2.next; } p3.next=NewListNode (carry%Ten); P3=p3.next; Carry/=Ten; }if(carry==1) p3.next=NewListNode (1);returnListnode.next; }}
C + + (from Network)
Class Solution { Public: ListNode*AddTwoNumbers (ListNode*L1, ListNode*L2) {int carry=0; ListNode*Res=NewListNode (0); ListNode*Head=Res while(L1&&L2) {Res -Next=NewListNode ((L1 -Val+L2 -Val+Carry%Ten); Carry=(L1 -Val+L2 -Val+Carry)/Ten; L1=L1 -Next L2=L2 -Next Res=Res -Next } while(L1) {Res -Next=NewListNode ((L1 -Val+Carry%Ten); Carry=(L1 -Val+Carry)/Ten; L1=L1 -Next Res=Res -Next } while(L2) {Res -Next=NewListNode ((L2 -Val+Carry%Ten); Carry=(L2 -Val+Carry)/Ten; L2=L2 -Next Res=Res -Next }if(Carry>0) {Res -Next= NewListNode (carry); }returnHead -Next }};
Copyright NOTICE: This article is nomasp Couvant original article, without permission is prohibited reprint! Welcome to my blog: http://blog.csdn.net/nomasp
Leetcode 2 Add Numbers