第一想法是顺着题目的原因,将两链表分别转化为一个数字,再将数字相加,然后把结果转化为字符串,存到答案链表中。但是数据太大会溢出!
所以,要在计算一对数字的过程当中直接存储一个结果,注意结果大于9时进位,删去最终链表的最后一个节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry=0; int x,y,z; ListNode* head = new ListNode(-1); ListNode* use = new ListNode(-1); ListNode* t = new ListNode(-1); head->next = t; while(l1 || l2) { if(!l1) { x = 0; }else x = l1->val; if(!l2) { y = 0; }else y = l2->val; z = x + y + carry; carry = 0; if(z>9) { carry = 1; z = z-10; } t->val = z; t->next = new ListNode(-1); use = t; t = t->next; t->next = NULL; if(l1) { l1 = l1->next; } if(l2) { l2 = l2->next; } } if(carry) { t->val = carry; t->next = new ListNode(-1); use = t; t = t->next; t->next = NULL; } t = head->next; use->next = NULL; return t; } };
原文地址:https://www.cnblogs.com/tornado549/p/9937709.html
时间: 2024-10-09 01:23:01