Add Two Numbers
两个十进制数,反向存储在单向链表里,每位数占一个节点。求和的链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int add(int a, int b, int &carry)
{
int c = a + b + carry;
carry = c / 10;
return c % 10;
}
ListNode *add_two_numbers(ListNode *l1, ListNode *l2)
{
ListNode *head = NULL, *rear = NULL;
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
int carry = 0;
while (l1 != NULL || l2 != NULL)
{
int val = 0;
if (l1 == NULL)
{
val = add(0, l2->val, carry);
l2 = l2->next;
}
else if (l2 == NULL)
{
val = add(l1->val, 0, carry);
l1 = l1->next;
}
else
{
val = add(l1->val, l2->val, carry);
l1 = l1->next;
l2 = l2->next;
}
ListNode *new_node = new ListNode(val);
if (head == NULL) head = new_node;
if (rear == NULL)
{
rear = new_node;
}
else
{
rear->next = new_node;
rear = rear->next;
}
}
if (carry != 0 && rear != NULL)
{
rear->next = new ListNode(carry);
}
return head;
}
Add Two Numbers相关推荐
- LeetCode 445. Add Two Numbers II--面试算法题--C++,Python解法
题目地址:Add Two Numbers II - LeetCode You are given two non-empty linked lists representing two non-neg ...
- [Leetcode] 445. Add Two Numbers II
问题: https://leetcode.com/problems/add-two-numbers-ii/#/description 思路:该题与"415. Add Strings" ...
- LeetCode之Add Two Numbers
LeetCode之Add Two Numbers 题目:You are given two linked lists representing two non-negative numbers. Th ...
- LeetCode刷题实战(2):Add Two Numbers
题2描述: 2 Add Two Numbers 29.10% Medium You are given two non-empty linked lists representing two non- ...
- leetcode算法—两数相加 Add Two Numbers
关注微信公众号:CodingTechWork,一起学习进步. 题目 Add Two Numbers: You are given two non-empty linked lists represen ...
- leetcode(二)—— Add Two Numbers(Python/C++)
Add Two Numbers | LeetCode OJ 逻辑是简单的,主要是处理进位,以及两序列长度不一致的情况: Python # 链表结点定义 class ListNode(object):d ...
- LeetCode题解:Add Two Numbers
LeetCode题解 说明:本人不是什么算法高手,部分内容参考了Google.stackoverflow.segmentfault中得到的一些解答或者代码.之所以去做Leetcode上的题是因为毕业工 ...
- LeetCode 445. Add Two Numbers II
LeetCode 445. Add Two Numbers II Solution1:我的答案 利用了栈,这样就不用翻转链表了... /*** Definition for singly-linked ...
- 【注意】LeetCode 2. Add Two Numbers
LeetCode 2. Add Two Numbers 这种沙比提怎么都写不对了??? Solution1:学习这种写法 /*** Definition for singly-linked list. ...
- LeetCode久不久来一题系列之Add Two Numbers
题目来源: https://leetcode.com/problems/add-two-numbers/description/ 题目: Add Two Numbers 题目描述: You are g ...
最新文章
- Go 知识点(14) — Go 多协程(单个协程触发panic会导致其它所有协程挂掉,每个协程只能捕获到自己的 panic 不能捕获其它协程)
- Java Windows注销用户,中止Windows从Java注销
- 使用函数_使用TEXT函数生成中文大写金额
- 奇妙的 10^n + 1
- 关于BT下载的一点事儿
- window10计算机策略,Win10秘笈:重置组策略/安全策略命令大全
- 黑科技 未来人们可用身体这7个部位来控制设备
- Tableau计算同比和环比任意天数据
- pos共识机制_PoW与PoS共识机制的优缺点介绍
- 产品没出来提前做推广_如果您不知道该怎么做,请提早和经常提出问题
- java中如何将一个对象,空值转换成空字符串
- java新手,写了个简单的计算器,求高手指点一二
- ThinkPad 声卡出现未安装任何音频输出设备
- C#之Base64编码解码
- 小胖机器人宣传语_智能机器人推广宣传语
- 微信JSAPI支付 - 服务商模式下子商户 统一下单的注意事项
- 淘宝/天猫邻家好货 API 返回值说明
- 告诫程序员们,大三/大四有必要去实习吗?
- 马云:今天互联网创业还靠免费就是找死
- 1062 最简分数(JAVA)