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;
}
}
}
}
};
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- iText学习(三)
- linux cd 命令的几个小技巧
- 解析xml文档总结(二)
- 漂亮网站---个人笔记
- android dialog
- leetcode-Add Two Numbers
- Java内部类
- SQL 表数据导出insert 语句
- android 将未签名的APK 包 , 转成签名的 (学习)
- thrift初步认识
- Code Sign error: No matching provisioning profile found: Your build settings specify a provisioni.
- swing的ItemListener的监听事件
- android快速开发框架
- python requests的安装与简单运用