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
Hide Tags
这题是链表遍历问题,容易处理。
#include <iostream>
using namespace std;
/**
* 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) {
if(l1==NULL) return l2;
if(l2==NULL) return l1;
int addOne=;
ListNode ret();
ListNode *p1=l1,*p2=l2,*pret=&ret;
while(){
if(p1==NULL&&p2==NULL&&addOne==) break;
if(p1==NULL&&p2==NULL){
pret->next = new ListNode((addOne)%);
pret = pret->next;
addOne = ;
continue;
}
if(p1==NULL){
pret->next = new ListNode((p2->val + addOne)%);
pret = pret->next;
addOne = (p2->val + addOne)/;
p2=p2->next;
continue;
}
if(p2==NULL){
pret->next = new ListNode((p1->val + addOne)%);
pret = pret->next;
addOne = (p1->val + addOne)/;
p1=p1->next;
continue;
}
pret->next = new ListNode((p1->val + p2->val + addOne)%);
pret = pret->next;
addOne = (p1->val + p2->val + addOne)/;
p1=p1->next;
p2=p2->next;
}
return ret.next;
}
}; int main()
{ return ;
}