2. Add Two Numbers
2016-04-10 10:20
246 查看
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
Subscribe to see which companies asked this question
题目分析:
这个题目的意思是输入是两个list,每个list代表的是一个数,list的每个节点值为这个数从低位到高位的值。
比如(2 -> 4 -> 3)表示的是342;(5 -> 6 -> 4)表示的是465.求这两个数的合,以同样的格式输出。
弄清楚题目就很好做了,每一位都按照加法的规则加上去就可以了。
代码:
/**
* 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) {
int carry=0;
ListNode * p1=new ListNode(0);
ListNode * head=p1;
while(l1 || l2 || (carry!=0))
{
int t1=0,t2=0;
if(l1)
{
t1=l1->val;
l1=l1->next;
}
if(l2)
{
t2=l2->val;
l2=l2->next;
}
int t=t1+t2+carry;
carry=t/10;
ListNode * p2=new ListNode(t%10);
p1->next=p2;
p1=p2;
}
p1->next=NULL;
return head->next;
}
};
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question
题目分析:
这个题目的意思是输入是两个list,每个list代表的是一个数,list的每个节点值为这个数从低位到高位的值。
比如(2 -> 4 -> 3)表示的是342;(5 -> 6 -> 4)表示的是465.求这两个数的合,以同样的格式输出。
弄清楚题目就很好做了,每一位都按照加法的规则加上去就可以了。
代码:
/**
* 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) {
int carry=0;
ListNode * p1=new ListNode(0);
ListNode * head=p1;
while(l1 || l2 || (carry!=0))
{
int t1=0,t2=0;
if(l1)
{
t1=l1->val;
l1=l1->next;
}
if(l2)
{
t2=l2->val;
l2=l2->next;
}
int t=t1+t2+carry;
carry=t/10;
ListNode * p2=new ListNode(t%10);
p1->next=p2;
p1=p2;
}
p1->next=NULL;
return head->next;
}
};
相关文章推荐
- C#中Ilist与list的区别小结
- C#中IList<T>与List<T>的区别深入解析
- C#对list列表进行随机排序的方法
- Vc++ 控件List Control用法总结
- C++实现的泛型List类分享
- C#使用IComparer自定义List类实现排序的方法
- C# Datagridview绑定List方法代码
- javascript radio list的实现细节(多浏览器兼容)
- c++ STL容器总结之:vertor与list的应用
- java实现List中对象排序的方法
- 大家注意vector, list, set, map成员函数erase
- ASP.NET―001:GridView绑定List、页面返回值具体实现
- List all the Databases on a SQL Server
- js Map List 遍历使用示例
- Java比较两个List的值是否相等的方法
- Java List双击事件实现方法
- velocity显示List与Map的方法详细解析
- 关于STL中list容器的一些总结
- 关于C#泛型列表List<T>的基本用法总结
- Java集合类中文介绍