Leetcode | | Add Numbers problem

Source: Internet
Author: User

Problem:

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

Ideas:

Two single-linked list of numbers added, and then the results are represented by a single linked list, to investigate the basic operation of the list, pay attention to the rounding

Attention:

Class Solution {public:    listnode *addtwonumbers (ListNode *l1, ListNode *l2) {
The two linked list pointers given by the topic L1, L2 Common sense point to the first valid element, not a pointer to a head node. Therefore, the returned pointer is also a pointer to a valid node, not to the head node.

Also: Linked list is best to use the presentation method of the lead node, convenient list operation!! The data field of the head node is useless, arbitrarily initialized, with its pointer field.

Code:

/** * 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) {int flag = 0;        listnode* tail = new ListNode (0);        listnode* ptr = tail;            while (L1! = NULL | | L2! = NULL) {int val1 = 0;                if (L1! = NULL) {val1 = l1->val;            L1 = l1->next;            } int val2 = 0;                if (L2! = NULL) {val2 = l2->val;            L2 = l2->next;            } int tmp = VAL1 + val2 + flag;            Ptr->next = new ListNode (tmp% 10);            flag = TMP/10;        PTR = ptr->next;        } if (flag = = 1) {Ptr->next = new ListNode (1);    } return tail->next; }};


Leetcode | | Add Numbers problem

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.