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

Leetcode:Add Two Numbers

时间:2015-02-07 09:08:17      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:add two numbers

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 preHead(0);
    ListNode *p = &preHead;
    int carry = 0;
    while (l1 || l2 || carry) {
        int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
        carry = sum / 10;
        p->next = new ListNode(sum % 10);
        p = p->next;
        l1 = l1 ? l1->next : l1;
        l2 = l2 ? l2->next : l2;
    }
    return preHead.next;
    }
};


Leetcode:Add Two Numbers

标签:add two numbers

原文地址:http://blog.csdn.net/wolongdede/article/details/43587595

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