Leetcode problem 2.Add, 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

The topic said that there are two linked lists stored two non-negative integers, linked list of the number is inverted, each node of the list is only one digit, let you add up the two numbers and then in the form of the list of the problem returned.

For example: There are two non-negative integers 342 and 465, plus 807, then in the list is 2->4->3,5->6->4, the returned 807 of the linked list should be 7->0->8.

The idea of this problem is not difficult, is to traverse two linked lists, the number of points, the only thing to pay attention to is two numbers added more than 10 to carry the problem.

The code is as follows:

1 classsolution{2  Public:3listnode* addtonumbers (listnode* L1, listnode*L2) {4listnode* result_list =NewListNode (0);5listnode* Cursor_pointer =result_list;6         intCarry_num =0;7          while(true){8             if(L1! =NULL) {9Carry_num + = l1->Val;TenL1 = l1->Next; One             } A             if(L2! =NULL) { -Carry_num + = l2->Val; -L2 = l2->Next; the             } -Cursor_pointer->val = carry_num%Ten; -Carry_num/=Ten; -             if(L1! = NULL | | L2! = NULL | | carry_num >0){ +Cursor_pointer = (Cursor_pointer->next =NewListNode (0)); -             } +             Else{ A                  Break; at             } -         } -         returnresult_list; -     } -};

Leetcode problem 2.Add, 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.