Leetcode 5. Two linked list elements add two Numbers

Source: Internet
Author: User

7 question: ADD-Numbers difficulty-medium

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

Answer:
Objective: To make an adder with carry (243+564 = 708)
The main point to consider is – two list of unequal cases and final rounding

Class Solution { Public: ListNode*AddTwoNumbers (ListNode*L1, ListNode*L2) {if(L1== NULL ||L2== NULL)returnL1== NULL ?L2:L1; ListNode Dummy (-1);//Virtual node, pointing to the list headerListNode*L= &Dummy int Carry= 0; int V1, v2,sum; while(L1||L2) {if(L1) {V1=L1 -Val L1=L1 -Next }Else{V1= 0; }if(L2) {v2=L2 -Val L2=L2 -Next }Else{v2= 0; }sum =V1+V2+Carry L -Next= NewListNode (sum % Ten);//post-interpolation, if it is C, write a post-interpolation functionCarry= sum / Ten; L=L -Next }when the//L1,L2 all reach the tail, the final carry is processed        if(Carry) {L -Next= NewListNode (carry); }returnDummy.Next }};

Leetcode 5. Two linked list elements add two Numbers

Related Article

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.