题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) { // write code here if(head1->val == 0) return head2; if(head2->val == 0) return head1; struct ListNode* H1last = (struct ListNode*)malloc(sizeof(struct ListNode)); H1last->val = -1; H1last->next = head1; struct ListNode* c1 = head1->next; struct ListNode* t; while(c1){ t = c1; c1 = c1->next; head1->next = t->next; t->next = H1last->next; H1last->next = t; } c1 = H1last->next; struct ListNode* H2last = (struct ListNode*)malloc(sizeof(struct ListNode)); H2last->val = -1; H2last->next = head2; struct ListNode* c2 = head2->next; while(c2){ t = c2; c2 = c2->next; head2->next = t->next; t->next = H2last->next; H2last->next = t; } c2 = H2last->next; int sum = 0; int i = 0; struct ListNode* H = NULL; while(c1 && c2){ sum = c1->val + c2->val; if(i == 1) sum++; struct ListNode* pt = (struct ListNode*)malloc(sizeof(struct ListNode)); pt->val = sum%10; pt->next = NULL; //printf("pt=%d\n",pt->val); if(sum>9) i=1; else i=0; if(H==NULL){ H = pt; } else{ pt->next = H; H = pt; } c1 = c1->next; c2 = c2->next; } if(c1 == NULL && c2 == NULL) return H; struct ListNode* tt = c1 == NULL? c2:c1; while(tt->next){ t = tt; tt = tt->next; if(i == 1){ t->val++; if(t->val == 10){ t->val = 0; } else i = 0; } t->next = H; H = t; } if(i == 1){ tt->val++; if(tt->val == 10){ struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode)); new->val = 0; new->next = H; H = new; tt->val = 1; } } tt->next = H; H = tt; return H; }