527人阅读 评论(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

class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *Node1=l1,*Node2=l2,*pre=l1;
int carrier=0;
int num;
while(Node1!=NULL&&Node2!=NULL)
{
num=Node1->val+Node2->val+carrier;
if(num<10)
{
Node1->val=num;
carrier=0;
}
else
{
Node1->val=num-10;
carrier=1;
}
pre=Node1;
Node1=Node1->next;
Node2=Node2->next;
}
while(Node1!=NULL)
{
num=Node1->val+carrier;
if(num<10)
{
Node1->val=num;
carrier=0;
}
else
{
Node1->val=num-10;
carrier=1;
}
pre=Node1;
Node1=Node1->next;
}
while(Node2!=NULL)
{
num=Node2->val+carrier;
if(num<10)
{
Node2->val=num;
pre->next=Node2;
carrier=0;
}
else
{
Node2->val=num-10;
pre->next=Node2;
carrier=1;
}
pre=Node2;
Node2=Node2->next;
}
if(carrier)
{
ListNode *node=new ListNode(1);
pre->next=node;
}
return l1;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：60311次
• 积分：1288
• 等级：
• 排名：千里之外
• 原创：66篇
• 转载：14篇
• 译文：0篇
• 评论：2条
博客专栏
 Leetcode面试题解 文章：31篇 阅读：21323
阅读排行
评论排行
最新评论