using java;ListNode单向链表相关
题目
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.
难度
medium(关键在于理解单向链表)
思路
- 输出也是一个链表,所以要有head指针;要在链表后面添加新的数据,所以要有tail指针
- 两数加法,考虑进位问题,先定义一个变量存储每位计算出来的值
- 循环什么时候停止?2个链表都为空并且进位为0的时候,得出while循环的条件
- 针对l1,l2不空的情况进行对应的相加和链表后移操作
- 处理进位
- 根据head是不是为空修改结果链表
代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=null,tail=null;
int curval=0;
while(l1!=null||l2!=null||curval!=0){
if(l1!=null){
curval+=l1.val;
l1=l1.next;
}
if(l2!=null){
curval+=l2.val;
l2=l2.next;
}
int outnum=curval%10;
curval/=10;
if(head==null){
head=new ListNode(outnum);
tail=head;
}else{
tail.next=new ListNode(outnum);
tail=tail.next;
}
}
return head;
}
}
注意点
- if(l1!=null) 和 if(l2!=null)不需要用else连接,因为这2句考虑都是不空,则加上数值并后移,如果为空,就不做任何操作
- curval/10是进位,在下次加上
- 画图,画图!链表类型的题画图思路清晰很多,head和tail都有实际意义