2. 两数相加
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *dummyhead = new ListNode(0); ListNode *cur = dummyhead; int carry = 0, sum = 0; while(l1 || l2){ int x = (l1 == nullptr? 0 : l1->val); int y = (l2 == nullptr? 0 : l2->val); sum = x + y + carry; carry = sum/10; sum = sum%10; cur->next = new ListNode(sum); cur = cur->next; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } if(carry == 1) cur->next = new ListNode(carry); return dummyhead->next; } };
思路:如果l1与l2不等长,那么空的部位用0补齐继续做加和运算;设置一个carry用来记录上一次加和的进位情况,并用在当前加和中;最后结束的时候要判断是否还有进位,如有,那么最后添加一个1(因为两个数相加的最大和不超过20)。
标签:ListNode,int,相加,next,l2,l1,carry,两数 From: https://www.cnblogs.com/xhhh/p/17186963.html