You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/** * C++ 代码 * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ classSolution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ ListNode head(-1); int f = 0; //标识进位 ListNode* pre = &head; ListNode* pa = l1, *pb = l2; int val = 0, a, b; while(pa!=nullptr||pb!=nullptr){ a = pa == nullptr?0:pa->val; b = pb == nullptr?0:pb->val; val = a + b + f; f = val / 10; val = val % 10; pre->next = new ListNode(val); pa=pa==nullptr?nullptr:pa->next; pb=pb==nullptr?nullptr:pb->next; pre = pre->next; } //最后判断是否有进位 if(f>0){ pre->next = new ListNode(f); } return head.next; } };