题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
class Solution { public: /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here stack<int> l1,l2; if(head1==nullptr) return head2; else if(head2==nullptr) return head1; while(head1 || head2) { if(head1) {l1.push(head1->val);head1 = head1->next;} if(head2) {l2.push(head2->val);head2 = head2->next;} } ListNode* res=nullptr; int canny=0; int num1 = min(l1.size(),l2.size()); int num2 = labs(l1.size()-l2.size()); for(int i=0;i<num1;i++) { canny += l1.top()+l2.top(); l1.pop(); l2.pop(); ListNode* cur= new ListNode(canny%10); canny = canny/10; cur->next = res; res = cur; } for(int i=0;i<num2;i++) { canny += l1.size()==0 ? l2.top() : l1.top(); l1.size()==0 ? l2.pop() : l1.pop(); ListNode* cur= new ListNode(canny%10); canny = canny/10; cur->next = res; res = cur; } if(canny>0) { ListNode* cur= new ListNode(canny); cur->next = res; res = cur; } return res; } };