题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead){
struct ListNode* res = NULL;
struct ListNode* cur = pHead;
while(cur){
struct ListNode* temp = cur->next;
cur->next = res;
res = cur;
cur = temp;
}
return res;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
struct ListNode* l1 = ReverseList(head1);
struct ListNode* l2 = ReverseList(head2);
struct ListNode* res = NULL;
int cnt = 0;
while(l1 || l2){
int x1 = l1 == NULL ? 0 : l1->val;
int x2 = l2 == NULL ? 0 : l2->val;
l1 = l1 == NULL ? NULL : l1->next;
l2 = l2 == NULL ? NULL : l2->next;
int sum = x1 + x2 + cnt;
cnt = sum/10;
struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = sum%10;
temp->next = res;
res = temp;
}
if(cnt > 0){
struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = cnt;
temp->next = res;
res = temp;
}
return res;
}
查看8道真题和解析
