Source: Internet
Author: User

Question:

You are given two linked lists representing two non-negative numbers. the digits are stored in reverse order and each of their nodes contain a single digit. add the two numbers and return it as a linked list.

Input:(2-> 4-> 3) + (5-> 6-> 4)
Output:7-> 0-> 8

An1_1:

`/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: listnode * addtwonumbers (listnode * L1, listnode * l2) {// start typing your C/C ++ Solution Below if (L1 = NULL & L2 = NULL) {return NULL ;} listnode * retlist = new listnode (0); listnode * tmplist = retlist; listnode * head1 = L1; listnode * Head2 = L2; int carry = 0; while (head1! = NULL & head2! = NULL) {int sum = carry + head1-> Val + head2-> val; carry = sum/10; tmplist-> next = new listnode (sum % 10 ); tmplist = tmplist-> next; head1 = head1-> next; head2 = head2-> next;} while (head1! = NULL) {int sum = carry + head1-> val; carry = sum/10; tmplist-> next = new listnode (sum % 10); tmplist = tmplist-> next; head1 = head1-> next;} while (head2! = NULL) {int sum = carry + head2-> val; carry = sum/10; tmplist-> next = new listnode (sum % 10); tmplist = tmplist-> next; head2 = head2-> next;} If (carry = 1) {tmplist-> next = new listnode (1);} tmplist = retlist; retlist = retlist-> next; delete tmplist; return retlist ;}};`

An1_2:

Related Keywords:

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.