题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* reverseList(ListNode* head){ if(head==nullptr) return nullptr; ListNode* cur=head; ListNode* node=nullptr; ListNode* next; while(cur!=nullptr){ next = cur->next; cur->next=node; node = cur; cur=next; } return node; } ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here if(head1==nullptr){ return head2;} if(head2==nullptr){ return head1;} head1 = reverseList(head1); head2 = reverseList(head2); int num; int jinwei=0; ListNode* resNode=new ListNode(-1); ListNode* resHead=resNode; while(head1!=nullptr&&head2!=nullptr){ num = head1->val + head2->val +jinwei; jinwei=0; if(num>9){ jinwei = 1; num=num-10;} ListNode* node = new ListNode(num); resNode->next = node; resNode = node; head1=head1->next; head2=head2->next; } if(head1==nullptr){ while(head2!=nullptr){ num = head2->val + jinwei; jinwei=0; if(num>9){ jinwei=1;num=num-10;} ListNode* node = new ListNode(num); resNode->next = node; resNode = node; head2=head2->next; } if(jinwei!=0){ ListNode* node = new ListNode(jinwei); jinwei=0; resNode->next = node; resNode = node; resNode->next=nullptr; } resHead->next = reverseList(resHead->next); return resHead->next; } if(head2==nullptr){ while(head1!=nullptr){ num = head1->val + jinwei; jinwei=0; if(num>9){ jinwei=1;num=num-10;} ListNode* node = new ListNode(num); resNode->next = node; resNode = node; head1=head1->next; } if(jinwei!=0){ ListNode* node = new ListNode(jinwei); jinwei=0; resNode->next = node; resNode = node; resNode->next=nullptr; } resHead->next = reverseList(resHead->next); return resHead->next; } return nullptr; } };