@requires_authorization
@author johnsondu
@create_time 2015.7.15 14:54
@url [add two numbers](https://leetcode.com/problems/add-two-numbers/)
/**
* 链表模拟大数相加
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*/
/**
* 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 *head = new ListNode(0);
ListNode *cur = head;
int carry = 0;
while(l1 || l2 || carry){
int tmp = carry;
if(l1 != NULL) {
tmp = tmp + l1->val;
l1 = l1->next;
}
if(l2 != NULL) {
tmp = tmp + l2->val;
l2 = l2->next;
}
carry = tmp / 10;
ListNode *node = new ListNode(tmp % 10);
cur->next = node;
cur = cur->next;
}
return head->next;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zone_programming/article/details/46893543