445. Add Two Numbers II | 链表的整数相加
来源:互联网 发布:川大网络教育入学考试 编辑:程序博客网 时间:2024/06/04 18:17
- Total Accepted: 15900
- Total Submissions: 34368
- Difficulty: Medium
- Contributors: Admin
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7
Subscribe to see which companies asked this question.
思路:先计算两个链表的长度,将长度大的链表的多余部分头插法,插入到新的链表中去,再同时编辑两个链表,将和设为新节点的值同样头插法插入到新的链表中去,再逆置新的链表,同时修改新链表节点的值,将大于10的取余作为进位,最后返回头结点即可。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode res = new ListNode(-1);res.next = null;ListNode p1 = l1, p2 = l2;int len1 = 0, len2 = 0;while (p1 != null) {len1++;p1 = p1.next;}while (p2 != null) {len2++;p2 = p2.next;}ListNode longNode = p1 = len1 > len2 ? l1 : l2;p2 = (len1 <= len2) ? l1 : l2;int dif = Math.abs(len1 - len2);while (dif > 0) {ListNode node = new ListNode(p1.val);node.next = res.next;res.next = node;p1 = p1.next;dif--;}len1 = len1 < len2 ? len1 : len2;while (p1 != null && p2 != null) {ListNode node = new ListNode(p1.val + p2.val);node.next = res.next;res.next = node;p1 = p1.next;p2 = p2.next;}int jinwei = 0, val;ListNode p = res.next, t;res.next = null;while (p != null) {t = p.next;val = (p.val + jinwei) % 10;jinwei = (p.val + jinwei) / 10;p.val = val;p.next = res.next;res.next = p;p = t;}res.val = jinwei;return jinwei > 0 ? res : res.next;}
0 0
- 445. Add Two Numbers II | 链表的整数相加
- leeecode 445. Add Two Numbers II 链表相加
- 大整数相加--链表结构正向存储--Add Two Numbers II
- 两个链表相加的和445. Add Two Numbers II
- 大整数相加链表实现(Add Two Numbers)
- Add Two Numbers 链表相加
- Add Two Numbers 链表相加
- Add Two Numbers Leetcode 链表相加
- Leetcode Add two numbers链表相加
- 【LeetCode】链表相加 Add Two Numbers
- leetcode -- 445. Add Two Numbers II 【栈 + 正整数相加】
- 445. Add Two Numbers II 两个数字相加 2
- leetcode_445. Add Two Numbers II 单链表表示的两个大数相加
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II**
- 445. Add Two Numbers II
- [NOIP2015] day2 T1 跳石头
- flask开发中蓝图与子域名
- winform窗体在当前显示窗口中居中
- SOJ 1042
- merge two sort list-leetcode 有序链表合并的二级指针简洁非递归解法
- 445. Add Two Numbers II | 链表的整数相加
- jQuery学习教程二十一: jQuery 遍历
- 每天一个 Linux 命令(52):ifconfig命令
- MySQL5.6中新增特性、不推荐使用的功能以及废弃的功能
- TensorFlow调试之一种很笨但行之有效的调试方案
- openstack, kvm, qemu-kvm以及libvirt之间的关系
- 读《 你首先是一个人,然后你才是程序员。》有感
- c++作业3
- iOS编译库文件时出现的问题,报错missing required architecture i386 in file 等.