题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
C++
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
string s1=trans(head1); //将链表的每个值变为字符,连接成字符串
string s2=trans(head2);
reverse(s1.begin(),s1.end()); //反转
reverse(s2.begin(),s2.end());
int n1=s1.size();
int n2=s2.size();
int n=n1>n2?n1:n2;
int res=0;
ListNode* head=new ListNode(0); //新建节点
//ListNode* phead=head;
head->next=nullptr;
for(int i=0;i<n;i++){ //大数相加+反序新建链表
int num1=n1>i?(s1[i]-'0'):0; //如果i已经超过字符串1的长度,赋值为0
int num2=n2>i?(s2[i]-'0'):0;
int num=(num1+num2+res)%10; //余数
res=(num1+num2+res)/10;
head->val=num; //为第一个节点赋值
ListNode* node=new ListNode(0); //新建节点
node->next=head; //反序
head=node;
}
if(res!=0){ //判断最后一次运算是否有进位,有进位,将最后新建的节点赋值,返回最后新建的节点,无进位,返回最后节点的前一个节点
head->val=res;
return head;
}
else{
return head->next;
}
}
string trans(ListNode* head){
string ans;
if(head==nullptr){
return ans;
}
//string ans;
while(head!=nullptr){
ans+=head->val+'0'; //整型变字符
head=head->next;
}
return ans;
}
};

查看8道真题和解析