题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
// 翻转
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = NULL;
struct ListNode* new_lis = dummy;
struct ListNode* p = head;
struct ListNode* q;
q = p->next;
while(p!=NULL){
p->next = dummy->next;
dummy->next = p;
p = q;
q = p->next;
}
return dummy->next;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
//翻转p1,p2
struct ListNode* p1 = reverseList(head1);
struct ListNode* p2 = reverseList(head2);
struct ListNode* resul = (struct ListNode*)malloc(sizeof(struct ListNode));
resul->next = NULL;
int temp = 0;
while(p1!=NULL || p2!=NULL){
int value = temp;
if(p1!=NULL){
value+=p1->val;
p1 = p1->next;
}
if(p2!=NULL){
value+=p2->val;
p2 = p2->next;
}
//新建结点并插入
struct ListNode *temp_node = (struct ListNode*)malloc(sizeof(struct ListNode));
temp_node->val = value%10;
temp_node->next = resul->next;
resul->next = temp_node;
temp = value/10;
}
//可能最高位多出来的进位
if(temp == 1){
struct ListNode *temp_node = (struct ListNode*)malloc(sizeof(struct ListNode));
temp_node->val = temp;
temp_node->next = resul->next;
resul->next = temp_node;
}
return resul->next;
}
查看15道真题和解析