码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode In C++] 2. Add Two Numbers

时间:2015-10-01 23:03:14      阅读:346      评论: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) {
        ListNode* temp1 = l1;
        ListNode* temp2 = l2;

        ListNode* head = NULL;
        ListNode* tail = NULL;
        int carry = 0;
        
        while(temp1 != NULL || temp2 != NULL) {
            int val1 = (temp1 != NULL)?temp1->val:0;
            int val2 = (temp2 != NULL)?temp2->val:0;
            int sum = (val1+val2+carry)%10;
            carry = (val1+val2+carry)/10;
            if(head == NULL) {
                head = new ListNode(sum);
                tail = head;
            }
            else {
                tail->next = new ListNode(sum);
                tail = tail->next;
            }
            temp1 = (temp1 != NULL)?temp1->next:NULL;
            temp2 = (temp2 != NULL)?temp2->next:NULL;
        }
        if(carry > 0) {
            tail->next = new ListNode(carry);
            tail = tail->next;
        }
        return head;
    }
};

 

[LeetCode In C++] 2. Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/wwwjjjfff/p/4851699.html

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