题目:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
代码:
/** * 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) { ListNode dummy(-1); ListNode *p = &dummy,*p1 = l1,*p2 = l2; int carry = 0; while(p1!=NULL || p2!=NULL){ const int v1 = p1==NULL?0:p1->val, v2 = p2==NULL?0:p2->val, v = (v1+v2+carry)%10; carry = (v1+v2+carry)/10; p->next = new ListNode(v); p = p->next; p1 = p1==NULL ? NULL : p1->next; p2 = p2==NULL ? NULL : p2->next; } if ( carry > 0 ) p->next = new ListNode(carry); return dummy.next; } };
Tips:
核心在于判断while停止条件:直到l1和l2都走完了才退出;如果l1或者l2先走完了,就当该位是0。
上面这种思路的好处是可以简化代码。
时间: 2024-10-10 14:20:11