单链表实现的加法,跟上学期数据结构学过的链表实现多项式加法类似,下面是完整代码,写的比较繁琐
也可以先把两个链表里的数取出来做加法,然后把结果再用链表表示,这样代码短一些,这里懒的写啦~
#include <iostream>
#include <cstring>#include <vector>
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) {
ListNode * ans = NULL;
ListNode * p, * q;
int carry = 0;
while(l1 != NULL && l2 != NULL){
int d = l1->val + l2->val + carry;
carry = d / 10;
if(ans == NULL){
ans = new ListNode(d % 10);
q = ans;
}
else {
p = new ListNode(d % 10);
q->next = p;
q = p;
}
l1 = l1->next;
l2 = l2->next;
}
while(l1 != NULL){
int d = l1->val + carry;
carry = d / 10;
p = new ListNode(d % 10);
q->next = p;
q = p;
l1 = l1->next;
}
while(l2 != NULL){
int d = l2->val + carry;
carry = d / 10;
p = new ListNode(d % 10);
q->next = p;
q = p;
l2 = l2->next;
}
if(carry){
p = new ListNode(1); q->next = p;
}
return ans;
}
};
void createList(ListNode* & l)
{
int digit;
cin >> digit;
if(digit == -1)return ;
l = new ListNode(digit);
createList(l->next);
}
int main()
{
ListNode * head1 = NULL;
ListNode * head2 = NULL;
createList(head1);
createList(head2);
Solution a;
ListNode * ans = a.addTwoNumbers(head1, head2);
while(ans != NULL){
cout << ans->val; ans = ans->next;
}
return 0;
}