1、 Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
Subscribe to see which companies asked this question.
思路一:将链表中的数字,分别放到两个容器内,这样就可以从后向前加啦~进位保存在变量CARRY中,余数就是相加后节点的 VAL,head指针不断向前
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
vector<int> nums1, nums2;
while(l1) {
nums1.push_back(l1->val);
l1 = l1->next;
}
while(l2) {
nums2.push_back(l2->val);
l2 = l2->next;
}
int m = nums1.size(), n = nums2.size();
int sum = 0, carry = 0;
ListNode *head = nullptr, *p = nullptr;
for(int i = m - 1, j = n - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
sum = carry;
if(i >= 0)
sum += nums1[i];
if(j >= 0)
sum += nums2[j];
carry = sum / 10;
p = new ListNode(sum%10);
p->next = head;
head = p;
}
return head;
}
思路二:不能反转也可以考虑他们位数差,从前向后加,这样还要定义一个pre节点嗯~
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int length1=1, length2=1;
ListNode* p=l1;
ListNode* q=l2;
while(p->next){
length1++;
p=p->next;
}
while(q->next){
length2++;
q=q->next;
}
int gap=length1-length2;
int l=0;
ListNode dummy(0);
ListNode* cur=&dummy;
ListNode* pre=&dummy;
if(gap>0){
p=l1;
q=l2;
pre->next=l1;
}
else{
p=l2;
q=l1;
pre->next=l2;
}
while(l!=abs(gap)){
p=p->next;
pre=pre->next;
l++;
}
while(p){
int carry=(p->val+q->val)/10;//jinwei
p->val=(p->val+q->val)%10;//yushu
pre->val=pre->val+carry;
pre=pre->next;
p=p->next;
q=q->next;
}
if(cur->val==0)
return cur->next;
else
return cur;
}
};