题解 | #牛群的能量值#
牛群的能量值
https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ #include <stdio.h> int getLength(struct ListNode* l1) { int count = 0; while (l1) { count++; l1 = l1->next; } return count; } struct ListNode* addEnergyValues(struct ListNode* l1, struct ListNode* l2 ) { // write code here int len1 = getLength(l1); int len2 = getLength(l2); int cin = 0; if (len1 >= len2) { struct ListNode* res = l1; struct ListNode* res1 = l1; while (l2) { int num = (l1->val + l2->val + cin) % 10; cin = (l1->val + l2->val + cin) / 10; l1->val = num; l1 = l1->next; l2 = l2->next; } while (l1) { int num = (l1->val + cin) % 10; cin = (l1->val + cin) / 10; l1->val = num; l1 = l1->next; } if (cin != 0) { struct ListNode* temp = malloc(sizeof(struct ListNode)); temp->val = cin; temp->next = NULL; while(res1){ if(res1->next== NULL){ res1->next=temp; res1=temp; break; } res1=res1->next; } } return res; } else { struct ListNode* res = l2; struct ListNode* res1 = l2; while (l1) { int num = (l1->val + l2->val + cin) % 10; cin = (l1->val + l2->val + cin) / 10; l2->val = num; l1 = l1->next; l2 = l2->next; } while (l2) { int num = (l2->val + cin) % 10; cin = (l2->val + cin) / 10; l2->val = num; l2 = l2->next; } if (cin != 0) { struct ListNode* temp = malloc(sizeof(struct ListNode)); temp->val = cin; temp->next = NULL; while(res1){ if(res1->next== NULL){ res1->next=temp; res1=temp; break; } res1=res1->next; } } return res; } }
优先判断链表l1,l2的长度,在长的链表进行相加操作,若计算到最后进位不为0,则进行插入操作