Clairezz_的博客

Never give up!

[leetcode][list] Add Two Numbers

题目:

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

36ms

/**
 * 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) {
	if (l2 == NULL) return l1;
	if (l1 == NULL) return l2;
	int digit = (l1->val + l2->val) % 10;
	int carry = (l1->val + l2->val) / 10;
	ListNode *head = new ListNode(digit);
	ListNode *tail = head;
	ListNode *p1 = l1->next, *p2 = l2->next;
	while (p1 != NULL && p2 != NULL){
		digit = (p1->val + p2->val + carry) % 10;
		carry = (p1->val + p2->val + carry) / 10;
		ListNode *p = new ListNode(digit);
		tail->next = p;
		tail = p;
		p1 = p1->next;
		p2 = p2->next;
	}
	ListNode *pp = p1;
	if (p2 != NULL) pp = p2;
	while (pp != NULL){
		digit = (pp->val + carry) % 10;
		carry = (pp->val + carry) / 10;
		ListNode *p = new ListNode(digit);
		tail->next = p;
		tail = p;
		pp = pp->next;
	}
	if (carry != 0){
		ListNode *p = new ListNode(carry);
		tail->next = p;
	}
	return head;
}
};


阅读更多
上一篇[leetcode][list] Remove Duplicates from Sorted List II
下一篇[leetcode][回溯] Combination Sum III
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭