题目:
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
int sum,bit;
sum = (l1->val+l2->val)%10;
bit = (l1->val+l2->val)/10;
ListNode * head=new ListNode(sum);
ListNode * tmp = head;
while(l1->next && l2->next)
{
sum = (l1->next->val+l2->next->val+bit)%10;
bit = (l1->next->val+l2->next->val+bit)/10;
tmp->next = new ListNode(sum);
tmp = tmp->next;
l1 = l1->next;
l2 = l2->next;
}
while(l1->next)
{
sum = (l1->next->val+bit)%10;
bit = (l1->next->val+bit)/10;
tmp->next = new ListNode(sum);
tmp = tmp->next;
l1 = l1->next;
}
while(l2->next)
{
sum = (l2->next->val+bit)%10;
bit = (l2->next->val+bit)/10;
tmp->next = new ListNode(sum);
tmp = tmp->next;
l2 = l2->next;
}
if(bit>0)
{
tmp->next = new ListNode(bit);
}
return head;
}
};
本文介绍了如何使用C++解决两个非负整数以链表形式表示并逆序存储的相加问题。通过定义链表节点结构,并实现将两个链表相加的功能,最终返回一个表示相加结果的链表。代码示例清晰地展示了从链表头节点开始遍历,进行数值加法和进位处理的过程。
505

被折叠的 条评论
为什么被折叠?



