LeetCode系列之Add Two Numbers
来源:互联网 发布:linux编译安装mysql 编辑:程序博客网 时间:2024/05/18 22:13
问题描述
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself
翻译一下:给两个单向非空链表所代表的非负整数,存储的时候会将他们逆置,你需要将它们加起来用链表输出
是不是有点难理解,还好它给了例子
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8
总体思路:两个链表相加,需要考虑,
- 进位
- 两个链表长度不同、相同
- 1和2叠加到一起
重点
由于我是将第一条链表的基础上进行操作,所以涉及到链表1最后为null且需要进位的情况,这时候可不能仅仅将l1赋值为新节点(由于java的值传递),所以需要有辅助节点记录最后一个非null节点
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int temp = -1; int add = 0; /**这里用一个辅助节点的用意就在于,由于我们是拿1的空间做的新 链表, 存在最后l1.next为null的情况,在处理进位的时候不能仅仅将l1被赋值为新节点(java的值传递),所以我们不能将希望全放在l1上, 这就是pre节点的作用,记录最后一个非null节点**/ ListNode pre = new ListNode(0); pre.next = l1; ListNode result = pre; while (l1 != null && l2 != null) { temp = l1.val + l2.val + add; add = temp / 10; temp = temp%10; l1.val = temp; pre = l1; l1 = l1.next; l2 = l2.next; } if (l1 == null && l2 != null) {//2比1长 pre.next = l2; while (add != 0 && l2 != null) { temp = l2.val + add; l2.val = temp % 10; add = temp / 10; pre = l2; l2 = l2.next; } if(add != 0){//2最后还有一个进位需要处理 ListNode last = new ListNode(add); pre.next = last; last.next = null; } return result.next; }else if (l2 == null && l1 != null) {//1比2长 while (add != 0 && l1 != null) { temp = l1.val + add; l1.val = temp % 10; add = temp / 10; pre = l1; l1 = l1.next; } if(add != 0){//1最后还有一个进位需要处理 ListNode last = new ListNode(add); pre.next = last; last.next = null; } return result.next; }else if (l1 == null && l2 == null){ if (add != 0) { ListNode last = new ListNode(add); pre.next = last; last.next = null; return result.next; }else { return result.next; } } return result.next; }
阅读全文
0 0
- 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题目之5 Add Two Numbers
- leetcode之路002 Add Two Numbers
- 【Leetcode】之Add Two Numbers问题
- LeetCode之2— Add Two Numbers
- Struts2--拦截器
- 数据类型:Undefined,Null——JavaScript知识小结05
- kmp深入
- 在Python结构体中存储值
- 多外部中断的优先级配置
- LeetCode系列之Add Two Numbers
- 美团编程大赛 数学题 拓展欧几里得和解是否存在
- vuejs路由使用的问题Error in render function: "TypeError: Cannot read property 'matched' of undefined"
- 快递实名制遭遇滑铁卢,背后原因在这里
- 解决Spring+Quartz无法自动注入bean问题
- CentOS 7 开放3306端口访问 iptables
- FTPrep, 2 Add Two Numbers
- 【Leetcode】【python】Arranging Coins
- 初级程序员的业务逻辑简单吗?