2. Add the Numbers

Source: Internet
Author: User

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

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode addtwonumbers (listnode L1, ListNode L2) {ListNode pl1=L1; ListNode PL2=L2; ListNode Head=NewListNode (0); ListNode P=Head; intCarry = 0; intsum;  while(pl1!=NULL&& pl2!=NULL) {sum= Pl1.val + Pl2.val +carry; Carry= sum>=10?1:0; P.next=NewListNode (sum%10); P=P.next; PL1=Pl1.next; PL2=Pl2.next; }         while(pl1!=NULL) {sum= Pl1.val +carry; Carry= sum>=10?1:0; P.next=NewListNode (sum%10); P=P.next; PL1=Pl1.next; }         while(pl2!=NULL) {sum= Pl2.val +carry; Carry= sum>=10?1:0; P.next=NewListNode (sum%10); P=P.next; PL2=Pl2.next; }        if(carry==1) {P.next=NewListNode (carry); }        returnHead.next; }}

2. Add the Numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.