题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ /* 链表实现的超过int位的算法,有实际价值 */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* ReverseList(ListNode* head) { // write code here if (head == nullptr || head->next == nullptr) return head; ListNode dummy = ListNode(-1); dummy.next = head; ListNode* pre = &dummy; ListNode* cur = head; ListNode* tmp; while (cur != nullptr) { // cout << cur->val << endl; tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } head->next = nullptr; return pre; } ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here ListNode *cur1 = ReverseList(head1); ListNode *cur2 = ReverseList(head2); // ListNode *dummy = new ListNode(-1); ListNode *cur = nullptr; int tmp; int carry = 0; while (cur1 != nullptr && cur2 != nullptr) { tmp = cur1->val + cur2->val + carry; carry = 0; if(tmp>=10) carry = 1; ListNode* newNode = new ListNode(tmp%10); newNode->next = cur; cur = newNode; cur1 = cur1->next; cur2 = cur2->next; } while(cur1!=nullptr){ tmp = cur1->val + carry; carry = 0; if(tmp>=10) carry = 1; cout<<tmp<<endl; ListNode* newNode = new ListNode(tmp%10); newNode->next = cur; cur = newNode; cur1 = cur1->next; } while(cur2!=nullptr){ tmp = cur2->val + carry; carry = 0; if(tmp>=10) carry = 1; ListNode* newNode = new ListNode(tmp%10); newNode->next = cur; cur = newNode; cur2 = cur2->next; } if(carry==1){ ListNode* newNode = new ListNode(1); newNode->next = cur; cur = newNode; } return cur; } };
用C++又解了一遍这个题目,思路更清晰了。