Leetcode--add Numbers

Source: Internet
Author: User
Tags add numbers

Problem Description:

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

Analysis: According to test instructions, according to the data structure of the linked list to add two numbers, mainly to investigate the chain list operation. A two-linked list can be traversed with two pointers. Be aware that there may be rounding in the end. The case where a node needs to be added, the detailed code such as the following:

/** * 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) {ListNode *p=l1, *q=l2;        ListNode *head=null,*cur=null;        if (!p&&!q) return head;        int flag=0;            while (p&&q) {int value= (p->val+q->val+flag)%10;            flag= (P->val+q->val+flag)/10;            ListNode *temp=new ListNode (value);                if (!cur) {cur=temp;            Head=cur;                } else {cur->next=temp;            Cur=temp;            } p=p->next;        q=q->next;            } while (p) {int value= (p->val+flag)%10;            flag= (P->val+flag)/10;            p->val=value;            cur->next=p;            Cur=p; p=p-≫next;            } while (q) {int value= (q->val+flag)%10;            flag= (Q->val+flag)/10;            q->val=value;            cur->next=q;            cur=q;        q=q->next;            } if (flag==1) {ListNode *temp=new ListNode (1);        cur->next=temp;    } return head; }};


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Leetcode--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.