题意
用一个链表代表每个数,但是这个链表是反的。比如123就是3->2->1。给两个这样的链表,求这两个链表代表的数之和,也用链表表示。
思路
正常模拟即可。按低位到高位每次相加,不要忘了进位。
时间复杂度O(n)
代码
/**
* 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* p = new ListNode(0);
ListNode* head = p;
int plus = 0, now = 0;
while (l1 || l2 || plus)
{
now = (l1?l1->val:0)+(l2?l2->val:0)+(plus?1:0);
p->next = new ListNode(now%10);
p = p->next;
if (now/10) plus = 1;
else plus = 0;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
return head->next;
}
};