题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: int getListNodesize(ListNode *node) { int count = 0; while (node != nullptr) { count++; node=node->next; } return count; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here ListNode *l = head1 , *r = head2; int ls = getListNodesize(l); int rs = getListNodesize(r); int lv[1000000]= {0}; int rv[1000000]= {0}; int size = ls; if (ls < rs) { ListNode *tmp = head1; head1 = head2; head2 = tmp; size = rs; } int diff = abs(ls - rs); for (int i=1; i<= size; ++i) { lv[i] = head1->val; head1 = head1->next; } for (int i=diff + 1; i<=size; ++i) { rv[i] = head2->val; head2 = head2->next; } // add int ts = size; while (size > 0) { int value = lv[size] + rv[size]; if (value > 9) { lv[size - 1]++; } lv[size] = value % 10; size--; } ListNode* head = new ListNode(-1); head->next =nullptr; ListNode *cur = head; for (int i=0; i<= ts; i++) { if (i==0 && lv[i] == 0) { continue; } ListNode* tmp = new ListNode(lv[i]); tmp->next = cur->next; cur->next =tmp; cur = cur->next; } return head->next; } };
简单记录一下不一样的思路,通过大数加法的办法,处理好链表数据到数组;进行加法后在生成所需的链表;减少了链表的操作,但是增加了空间的消耗;
#晒一晒我的offer#