码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers

时间:2015-04-05 18:53:07      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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

代码如下:

/**
 * 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 )
            return l2;
        if(l2 == NULL)
            return l1;
        ListNode *l3=NULL, *node;
        ListNode *pHead1 = l1, *pHead2 = l2, *pHead3 = l3;
        int up = 0;
        while (pHead1 != NULL && pHead2 != NULL){
            node = new ListNode(pHead1->val + pHead2->val + up);
            up = node->val / 10;
            node->val = node->val %10;
            if (l3 == NULL){
                l3 = pHead3 = node;
            }
            else{
                pHead3->next = node;
                pHead3 = pHead3->next;
            }
            pHead1 = pHead1->next;
            pHead2 = pHead2->next;
        }
        while (pHead1 != NULL){
            node = new ListNode(pHead1->val + up);
            up = node->val / 10;
            node->val = node->val % 10;
            pHead3->next = node;
            pHead1 = pHead1->next;
            pHead3 = pHead3->next;
        }
        while (pHead2 != NULL){
            node = new ListNode(pHead2->val + up);
            up = node->val / 10;
            node->val = node->val % 10;
            pHead3->next = node;
            pHead2 = pHead2->next;
            pHead3 = pHead3->next;
        }
        if (up > 0){
            node = new ListNode(up);
            pHead3->next = node;
        }
        return l3;
    }
};

 

Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/Scorpio989/p/4394460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!