关闭

[leetcode][list] Add Two Numbers

137人阅读 评论(0) 收藏 举报
分类:

题目:

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;
}
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32465次
    • 积分:2074
    • 等级:
    • 排名:第18451名
    • 原创:182篇
    • 转载:8篇
    • 译文:0篇
    • 评论:2条
    最新评论