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
-
#include <iostream>
-
#include <map>
-
#include <vector>
-
#include <string>
-
-
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* current_result = new ListNode(0);
-
current_result->next = l1;
-
ListNode* result = l1;
-
int val;
-
-
int over_ten_flag = 0;
-
-
while(l1){
-
if(l2){
-
val = (over_ten_flag + l1->val + l2->val) % 10;
-
over_ten_flag = (over_ten_flag + l1->val + l2->val) / 10;
-
l2 = l2->next;
-
} else{
-
break;
-
}
-
current_result->next->val = val;
-
current_result = current_result->next;
-
l1 = l1->next;
-
}
-
-
while(l1){
-
if ( l1->val != 9 || over_ten_flag == 0 ){
-
current_result->next->val = current_result->next->val + over_ten_flag;
-
over_ten_flag = 0;
-
break;
-
}
-
current_result->next->val = 0;
-
current_result = current_result->next;
-
l1 = l1->next;
-
}
-
-
if(l2) {
-
current_result->next = l2;
-
-
while(l2){
-
if ( l2->val != 9 || over_ten_flag == 0 ){
-
current_result->next->val = current_result->next->val + over_ten_flag;
-
over_ten_flag = 0;
-
break;
-
}
-
current_result->next->val = 0;
-
current_result = current_result->next;
-
l2 = l2->next;
-
}
-
}
-
-
if(over_ten_flag){
-
ListNode* temp_node = new ListNode(1);
-
current_result->next = temp_node;
-
}
-
-
return result;
-
}
-
};
-
-
int main(){
-
Solution* a = new Solution();
-
ListNode* n1 = new ListNode(5);
-
ListNode* n2 = new ListNode(4);
-
ListNode* n3 = new ListNode(3);
-
ListNode* n4 = new ListNode(5);
-
ListNode* n5 = new ListNode(6);
-
ListNode* n6 = new ListNode(4);
-
-
n1->next = n2;
-
// n2->next = n3;
-
-
// n4->next = n5;
-
// n5->next = n6;
-
-
ListNode* result = a->addTwoNumbers(n1, n4);
-
-
cout << result->val << result->next->val << endl;
-
-
bool negtive = 3>0;
-
cout << negtive;
-
-
system("pause");
-
return 0;
-
}
阅读(568) | 评论(0) | 转发(0) |