您的位置:首页 > 其它

002Add Two Numbers

2015-08-25 13:52 218 查看

002Add Two Numbers

目录

002Add Two Numbers
目录
题目内容

我的代码

小记

第二题比较简单,应该是最优的,只要处理好链表和地址即可,需要学习下函数中malloc和new关于内存的区别。

malloc与new

题目内容

==

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* tmp(0);
int i;
ListNode* first = (ListNode*)malloc(sizeof(ListNode));
tmp = first;
int remain=0;
while(l1!=NULL&&l2!=NULL)
{
ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));
temp_list->val = (remain + l1->val + l2->val)%10;
remain = (remain + l1->val + l2->val)/10;
tmp->next = temp_list;
tmp = temp_list;
l1 = l1->next;
l2 = l2->next;
}
while(l1!=NULL)
{
ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));
temp_list->val = (remain + l1->val)%10;
remain = (remain + l1->val)/10;
tmp->next = temp_list;
tmp = temp_list;
l1 = l1->next;
}
while(l2!=NULL)
{
ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));
temp_list->val = (remain + l2->val)%10;
remain = (remain + l2->val)/10;
tmp->next = temp_list;
tmp = temp_list;
l2 = l2->next;
}
if(remain!=0)
{
ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));
temp_list->val = remain;
tmp->next = temp_list;
tmp = temp_list;
}
tmp->next = NULL;

return first->next;
}
};


小记

认真即可,想清楚具体流程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: