题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
/*
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur) {
ListNode* next = cur->next;
cur->next = pre;
pre=cur;
cur=next;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* cur1 = reverseList(head1);//翻转链表
ListNode* cur2 = reverseList(head2);//翻转链表
ListNode* resHead=nullptr;
int cnt = 0;
int x1=0,x2=0,sum=0;
while(cur1 || cur2) { //如果两个值的加和>10,就会产生进位,这个用来存储进位
if(cur1==nullptr) x1=0;
else x1=cur1->val;
if(cur2==nullptr) x2=0;
else x2=cur2->val;
sum = x1+x2+cnt;
cnt = sum / 10;
ListNode* tmpNode = new ListNode(sum%10);
tmpNode->next = resHead;
resHead = tmpNode;
if(cur1) cur1=cur1->next;
if(cur2) cur2=cur2->next;
}
// 如果cnt>0 那么就说明存在进位还得插入一个节点
if(cnt > 0) {
ListNode* newNode = new ListNode(cnt);
newNode->next = resHead;
resHead = newNode;
}
return resHead;
}
};*/
class Solution {
public:
ListNode* addInList(ListNode* head1, ListNode* head2) {
if(head1==nullptr) return head2;
if(head2==nullptr) return head1;
// 使用两个辅助栈,利用栈先进后出,相当于反转了链表
stack<ListNode*> s1,s2;
ListNode* p1 = head1;
ListNode* p2 = head2;
ListNode* resHead=nullptr;
while(p1) {
s1.push(p1);
p1=p1->next;
}
while(p2) {
s2.push(p2);
p2=p2->next;
}
int sum = 0;
int x1=0,x2=0,cnt=0;
while(!s1.empty() || !s2.empty()) {
if(!s1.empty()) x1 = s1.top()->val;
else x1=0;
if(!s2.empty()) x2 = s2.top()->val;
else x2=0;
sum = x1+x2+cnt;
cnt = sum / 10;
ListNode* tmpNode = new ListNode(sum % 10);
tmpNode->next = resHead;
resHead = tmpNode;
if(!s1.empty()) s1.pop();
if(!s2.empty()) s2.pop();
}
if(cnt>0) {
ListNode* newNode = new ListNode(cnt);
newNode->next = resHead;
resHead=newNode;
}
return resHead;
}
};
顺丰集团工作强度 337人发布