(leetcode)2. 两个链表相加Add Two Numbers--Java
来源:互联网 发布:加强网络舆情监管 编辑:程序博客网 时间:2024/05/18 17:41
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
这个题思路很简单,主要遇到的问题:
1.在处理链表的时候, ListNodetemp=sum; 中的temp 和sum 可以理解为指针,所以,每次新new 一个sum的话,指向的对象肯定就变化了,所以new的时候只能new ,sum.next。
2.忘了怎么处理怎么到达表头了,这个很简单,直接定义两个变量指向表头,每次只改变一个,所以另一个一直都在表头的位置。
publicclassSolution {
publicListNode addTwoNumbers(ListNodel1, ListNodel2) {
ListNodesum=newListNode(0);
ListNodetemp=sum;
inti=0;
while(l1!=null||l2!=null||i!=0){
if(l1==null){
l1=newListNode(0);
}
if(l2==null){
l2=newListNode(0);
}
if(sum==null){
sum=newListNode(0);
}
if(l1.val+l2.val+i<10){
sum.next=newListNode(l1.val+l2.val+i);
sum=sum.next;
i=0;
}else{
sum.next=newListNode(l1.val+l2.val+i-10);
sum=sum.next;
i=1;
}
l1=l1.next;
l2=l2.next;
}
returntemp.next;
}
}
0 0
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- LeetCode Add Two Numbers两个链表数值相加
- LeetCode | Add Two Numbers(两个链表相加)
- Add Two Numbers Leetcode 链表相加
- Leetcode Add two numbers链表相加
- 【LeetCode】链表相加 Add Two Numbers
- LeetCode 2. Add Two Numbers -- 两个链表按序从头到尾相加,记录进位
- leetcode Add Two Numbers 两个数相加
- LeetCode-2. Add Two Numbers(链表实现数字相加)
- 【LeetCode】2.Add Two Numbers两个单链表相加
- Add Two Numbers 把两个以链表形式表示的数相加 @LeetCode
- leetcode 5. 两个链表逐个元素相加 Add Two Numbers
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- Add Two Numbers 两个链表相加 python
- [Leetcode]Add Two Numbers 链表实现大数字相加
- 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】
- Add Two Numbers 链表相加
- Add Two Numbers 链表相加
- 不要62 HDU
- 多线程开发1--线程的基本操作
- (leetcode)1. 查找数组中两个数之和为给定值Two Sum---Java
- Java 数据结构和算法 排序
- 4.《MySQL必知必会》分组与联合
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- 连结及索引、优化器相关
- Min Stack
- Mysql学习笔记六——order by 排序
- JavaScript如何动态生成表格
- 39. Combination Sum 40. Combination Sum II 216. Combination Sum III
- Python学习笔记56(爬虫:煎蛋网上的妹子图)
- mybatis框架,细节处理
- 浅谈React.createElement()方法