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
给两个链表,数字是按数的反向顺序存储在链表中,如 2 -> 4 -> 3 ,表示的是 342 ,这个其实可以不关心 。。。
处理方法:
按照二进制加、字符串数字相加的类似处理方法
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode* H = new ListNode(0);
ListNode* tmp=H;
int c=0,sum=0;
int digitA,digitB;
while(l1 || l2 || c>0)
{
digitA = l1?l1->val:0;
digitB = l2?l2->val:0;
sum = digitA + digitB + c;
c = sum/10;
ListNode* p = new ListNode(sum%10);
tmp->next = p;
tmp=tmp->next;
if(l1)
l1=l1->next;
if(l2)
l2=l2->next;
}
return H->next;
}
};
int main()
{
ListNode* l1 =new ListNode(5);
ListNode* l2 =new ListNode(5);
Solution s;
ListNode* tmp = s.addTwoNumbers(l1,l2);
while(tmp)
{
cout<<tmp->val<<" ";
tmp=tmp->next;
}
return 0;
}