您的位置:首页 > 其它

leetcode002 Add Two Numbers

2015-09-26 22:26 417 查看
题目:

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

思路:

一个链表,代表两个数字,从低位往高位加,用一个链表输出结果。无太巧妙的思路,就是从低位往高位一个个加,用一个bool值表示进位。不过要注意一些易错的地方:1、注意两个链表的长度可能不相等 2、有可能两个链表都走到末尾,但是还剩下一个进位不要忘记加上。主要易错点就是这两点

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
bool isAdd = false;
ListNode* root = NULL;
ListNode* cur = root;
while(l1 != NULL || l2 != NULL || isAdd)
{
int t = isAdd;
if(l1 != NULL) {
t += l1->val;
l1 = l1->next;
}
if(l2 != NULL) {
t += l2->val;
l2 = l2->next;
}

if(t >= 10){
t = t - 10;
isAdd = true;
}else{
isAdd = false;
}

if(cur == NULL){
root = new ListNode(t);
cur = root;
}else{
ListNode* newNode = new ListNode(t);
cur->next = newNode;
cur = cur->next;
}

}

return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: