2. Add Two Numbers

发布时间:2017-6-29 10:40:52编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"2. Add Two Numbers",主要涉及到2. Add Two Numbers方面的内容,对于2. Add Two Numbers感兴趣的同学可以参考一下。

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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

/**
 * 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) {
        if(l1 == NULL && l2 == NULL)
            return NULL;
        
        ListNode *head = NULL;
        ListNode *pNode = NULL;
        ListNode *pNext = NULL;
        
        int jinwei = 0;
        
        while(l1 != NULL && l2 != NULL)
        {
            pNext = new ListNode(l1->val + l2->val + jinwei);
            jinwei = pNext->val/10;
            pNext->val = pNext->val%10;
            
            if(head == NULL)
            {
                head = pNode = pNext;
            }
            else
            {
                pNode->next = pNext;
                pNode = pNode->next;
            }
            l1 = l1->next;
            l2 = l2->next;
        }
        
        while(l1 != NULL)
        {
            pNext = new ListNode(l1->val + jinwei);
            jinwei = pNext->val/10;
            pNext->val = pNext->val%10;
            pNode->next = pNext;
            pNode = pNode->next;
            l1 = l1->next;
        }
        
         while(l2 != NULL)
        {
            pNext = new ListNode(l2->val + jinwei);
            jinwei = pNext->val/10;
            pNext->val = pNext->val%10;
            pNode->next = pNext;
            pNode = pNode->next;
            l2 = l2->next;
        }
        
        if(jinwei > 0)
        {
            pNext = new ListNode(jinwei);
            pNode->next = pNext;
            jinwei = 0;
        }
        
        return head;
    }
};




上一篇:SMTP错误码/建议解决方法
下一篇:JAVA 重载,返回类型

相关文章

关键词: 2. Add Two Numbers

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款