solution.cpp 759 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
struct ListNode
{
	int val;
	struct ListNode *next;
};
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2)
{
	struct ListNode *pp = NULL, *p = l1;
	struct ListNode *qp = NULL, *q = l2;
	int carry = 0;
	while (p != NULL && q != NULL)
	{
		p->val += q->val + carry;
		carry = 0;
		if (p->val >= 10)
		{
			carry = 1;
			p->val -= 10;
		}
		pp = p;
		p = p->next;
		qp = q;
		q = q->next;
	}
	if (q)
	{
		pp->next = p = q;
		qp->next = NULL;
	}
	while (carry && p)
	{
		p->val += carry;
		carry = 0;
		if (p->val >= 10)
		{
			carry = 1;
			p->val -= 10;
		}
		pp = p;
		p = p->next;
	}
	if (carry)
	{
		struct ListNode *n = (struct ListNode *)malloc(sizeof(struct ListNode));
		n->val = 1;
		n->next = NULL;
		pp->next = n;
	}
	return l1;
}