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) {
int n1,n2,r,flag = 0;
ListNode result(0);
ListNode *p,*node;
p = &result;
while( (l1!=NULL) && (l2!=NULL) )
{
n1 = l1->val;
n2 = l2->val;
r = n1 + n2 + flag;
node = new ListNode(0);
node->val = r % 10;
flag = (r/10 > 0) ? 1 : 0;
p->next = node;
p = node;
l1 = l1->next;
l2 = l2->next;
}
if(l1 == NULL)
l1 = l2;
while(l1!=NULL)
{
node = new ListNode(0);
node->val = l1->val + flag;
flag = (node->val/10 == 0) ? 0 : 1;
node->val = (node->val/10 == 0) ? node->val : 0;
p->next = node;
p = node;
l1 = l1->next;
}
if(flag)
{
node = new ListNode(1);
p->next = node;
}
p = result.next;
return p;
}
};
本文介绍了如何通过给定的两个链表,表示两个非负整数,进行相加操作,并返回结果作为新的链表。重点在于解决进位问题,通过迭代遍历链表节点,实现数值的加法运算。
501

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



