leetcode-Add Two Numbers

来源:互联网 发布:中国电信盒子安装软件 编辑:程序博客网 时间:2024/06/06 20:41

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

思路较简单,主要是注意进位等情况

/**
 * 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(l1==NULL)
{
return l2;
}
else if(l2==NULL)
{
return l1;
}
else
{
int carry=0;
int temp=0;
ListNode *p1=l1;
ListNode *p2=l2;
ListNode *pre;
while(( p1!=NULL ) && ( p2!=NULL ))
{
temp=p1->val+p2->val+carry;
p1->val=temp%10;
if (temp>9)
{
carry=temp/10;
temp=0;
if((p1->next==NULL)&&(p2->next==NULL))
{
ListNode *newNode=(ListNode *)malloc(sizeof(ListNode));
newNode->val=carry;
newNode->next=NULL;
p1->next=newNode;
return l1;
}
}
else
{
carry=0;
temp=0;
if((p1->next==NULL)&&(p2->next==NULL))
{

return l1;
}
}
pre=p1;
p1=p1->next;
p2=p2->next;
}
if(p2==NULL)
{
while(p1!=NULL)
{
temp=p1->val+carry;
p1->val=temp%10;
if (temp>9)
{
carry=temp/10;
temp=0;
if(p1->next==NULL)
{
ListNode *newNode=(ListNode *)malloc(sizeof(ListNode));
newNode->val=carry;
newNode->next=NULL;
p1->next=newNode;
return l1;
}
}
else
{
carry=0;
temp=0;
if(p1->next==NULL)
{
return l1;
}
}
p1=p1->next;
}
}
else if(p1==NULL)
{
while(p2!=NULL)
{
temp=p2->val+carry;
ListNode *newNode=(ListNode *)malloc(sizeof(ListNode));
newNode->val=temp%10;
newNode->next=NULL;
pre->next=newNode;
pre=newNode;
if (temp>9)
{
carry=temp/10;
temp=0;
if(p2->next==NULL)
{
ListNode *newNode=(ListNode *)malloc(sizeof(ListNode));
newNode->val=carry;
newNode->next=NULL;
pre->next=newNode;
return l1;
}
}
else
{
carry=0;
temp=0;
if(p2->next==NULL)
{
return l1;
}
}


p2=p2->next;
}
}
}
    }
};

0 0
原创粉丝点击