题目描述
知识点
链表、数学
我的实现
码前思考
大整数加法的模拟题
代码实现
//类似于大整数加法,只不过将数组变成了单链表
//注意特判一些特殊情况
/**
* 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* head = NULL;
//当前结点
ListNode* point = NULL;
//进位
int carry = 0;
//仿照大整数加法进行操作
//两者同时不为NULL
while(l1 != NULL && l2 != NULL){
int res = l1->val + l2->val + carry;
carry = res/10;
if(head == NULL){
head = new ListNode(res%10);
point = head; //指向同一个结点
}else{
ListNode* cur = new ListNode(res%10);
point->next = cur;
point = cur;
}
l1=l1->next;
l2=l2->next;
}
//对于没有读取完的l1结点
while(l1 != NULL){
int res = l1->val + carry;
carry = res / 10;
ListNode* cur = new ListNode(res%10);
point->next = cur;
point = cur;
l1=l1->next;
}
//对于没有读取完的l2结点
while(l2 != NULL){
int res = l2->val + carry;
carry = res / 10;
ListNode* cur = new ListNode(res%10);
point->next = cur;
point = cur;
l2=l2->next;
}
//如果还有进位
while(carry!=0){
ListNode* cur = new ListNode(carry);
point->next = cur;
point = cur;
carry = carry / 10;
}
return head;
}
};
码后反思
细心就好
二刷代码
/**
* 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* dummyNode = new ListNode(0);
ListNode* end = dummyNode;
int carry = 0;
ListNode* p1=l1;
ListNode* p2=l2;
//开始计算
while(p1!=NULL && p2!=NULL){
int r = p1->val + p2->val + carry;
ListNode* newNode = new ListNode(r%10);
carry = r/10;
end->next = newNode;
end = newNode;
p1=p1->next;
p2=p2->next;
}
//查看是谁无了
while(p1!=NULL){
int r = p1->val+carry;
ListNode* newNode = new ListNode(r%10);
carry = r/10;
end->next = newNode;
end = newNode;
p1=p1->next;
}
while(p2!=NULL){
int r = p2->val+carry;
ListNode* newNode = new ListNode(r%10);
carry = r/10;
end->next = newNode;
end = newNode;
p2=p2->next;
}
if(carry!=0){
ListNode* newNode = new ListNode(carry);
end->next = newNode;
}
return dummyNode->next;
}
};