Add Two Numbers
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
题目意思就是 求俩个整数相加,整数是倒着表示的
我开始是用 l1 来存答案
/**
* 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;
}
ListNode *ans = l1;
int cur = 0;
ListNode *p=l1;
while (l1 && l2){
int temp = l1->val + l2->val + cur;
l1->val = temp % 10;
cur = temp / 10;
p = l1;
l2 = l2->next;
if (l1->next == NULL && l2!=NULL){
l1->next = new ListNode(0);
l1 = l1->next;
break;
}
l1 = l1->next;
}
if (l1 == NULL && l2 == NULL && cur){
ListNode * ff = ans;
while (ff->next != NULL){
ff = ff->next;
}
ff->next = new ListNode(1);
}
else if (l2!=NULL){
while (l2 != NULL){
int temp = cur + l2->val;
l1->val = temp % 10;
cur = temp / 10;
l2 = l2->next;
p = l1;
l1->next = new ListNode(0);
l1 = l1->next;
}
if (cur){
l1->val = 1;
}
}
else if (l1!=NULL)
while(l1 != NULL){
int temp = cur + l1->val;
l1->val = temp % 10;
cur = temp /= 10;
p = l1;
if (l1->next == NULL && cur){
l1->next = new ListNode(cur);
l1->next->val = cur;
l1 = l1->next;
break;
}
l1 = l1->next;
}
// cout << ans->val << " " << ans->next->val << endl;
//cout << "fuck" << p->val << endl;
if (p->next && p->next->val == 0){
p->next = NULL;
}
return ans;
}
};最好新建个链表保存答案
/**
* 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) {
ListNode *l=new ListNode(0);
ListNode *cur = l;
if (l1 == NULL){
return l2;
}
if (l2 == NULL){
return l1;
}
int ans = 0;
int flag = 1;
while (l1 != NULL || l2 != NULL){
int val1 = 0;
if (l1 != NULL){
val1 = l1->val;
l1 = l1->next;
}
int val2 = 0;
if (l2 != NULL){
val2 = l2->val;
l2 = l2->next;
}
cur->next= new ListNode((val1 + val2 + ans) % 10);
ans = (val1 + val2 + ans) / 10;
cur = cur->next;
}
if (ans != 0){
cur->next = new ListNode(ans);
}
return l->next;
}
};
浙公网安备 33010602011771号