链表翻转后节点相加(使用栈模拟),如果有进位则记录,产生新的结点以头插法插入到新的链表;注意加完以后需要检查最后是否有进位,如果有进位就还需要再插入一个新的节点。
/** * 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* addInList(ListNode* head1, ListNode* head2) { // write code here //链表翻转后节点相加(使用栈模拟),如果有进位则记录,产生新的结点以头插法插入到新的链表; ListNode* rst = NULL; stack<ListNode*> head1_stack; stack<ListNode*> head2_stack; ListNode* p = head1; ListNode* q = head2; while(p) { head1_stack.push(p); p=p->next; } while(q) { head2_stack.push(q); q=q->next; } int carry = 0; while(!head1_stack.empty() && !head2_stack.empty()) { p = head1_stack.top(); q = head2_stack.top(); int sum = p->val + q->val + carry; carry = sum / 10; sum = sum % 10; rst = insert_node(rst,sum); head1_stack.pop(); head2_stack.pop(); } if(!head1_stack.empty()) { //head1更长; while(!head1_stack.empty()) { p = head1_stack.top(); int sum = p->val + carry; carry = sum / 10; sum = sum % 10; rst = insert_node(rst,sum); head1_stack.pop(); } }else if(!head2_stack.empty()) { //head2更长; while(!head2_stack.empty()) { q = head2_stack.top(); int sum = q->val + carry; carry = sum / 10; sum = sum % 10; rst = insert_node(rst,sum); head2_stack.pop(); } } //看最后是否有进位; if(carry > 0) { rst = insert_node(rst,carry); } return rst; } //头插法插入节点,返回头指针; ListNode* insert_node(ListNode* head, int n) { ListNode* new_node = new ListNode(n); if(head == NULL) { head = new_node; }else{ new_node->next = head; head = new_node; } return head; } };