javal链表相加求和!
2017-07-27 13:58
197 查看
面试遇到一算法题:
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
琢磨了一阵子,希望可以帮到有缘人。代码如下:
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
琢磨了一阵子,希望可以帮到有缘人。代码如下:
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode listNode= new ListNode(0); ListNode p = new ListNode(0); p = listNode; int sum = 0; while (l1 != null || l2 != null || sum != 0) { if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } p.next = new ListNode(sum % 10); sum = sum / 10; p = p.next; } return listNode.next; } }
相关文章推荐
- leetcode之链表类之链表归并类-----OJ 2/21/23/445 链表相加求和 链表归并
- lintcode-链表求和
- 链式A+B有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。 给定两个链表ListNode* A,ListN
- lc#2使用链表实现两数相加
- lintcode 链表求和
- 数据结构_数组与广义表_矩阵的十字链表存储稀疏矩阵相加
- Day6-(链表表示)两个数相加
- 多项式相加(链表的汇编语言实现)
- 链表实现大数相加和大数相乘
- 数据结构:链表创建、显示、求和、插入、删除等操作的代码实现
- 链表求和
- java 几个数相加求和
- 链表系列之单链表——使用单链表实现大整数相加
- 利用链表计算多项式的相加
- 两个链表相加
- 链表求和(LintCode)
- 两个链表相加
- 微软一面:输入两个数,相加求和,二进制输出
- 两个单链表生成相加链表
- LintCode-[中等] 221. 链表求和 II