LeetCode#两数相加#Java实现
class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int length_l1=0;
if (l1!=null){
ListNode p=l1;
while (p!=null){
length_l1++;
p=p.next;
}
}
int length_l2=0;
if (l2!=null){
ListNode p=l2;
while (p!=null){
length_l2++;
p=p.next;
}
}
//使用尾插法创建带头节点的链表存储结果,不返回头节点,返回header.next
ListNode header=new ListNode(0);//头节点
header.next=null;//头节点指针指向null,防止指向脏数据
ListNode r;
r=header;//通过r对链表操作,r始终指向链表最后一个节点
int count=0;//进位
int i=0;
ListNode p=l1;
ListNode q=l2;
while (p!=null&&q!=null){
ListNode newNode;
if (p.val+q.val+count>=10){
newNode=new ListNode( p.val+q.val+count-10);
count=1;
}else {
newNode=new ListNode(p.val+q.val+count);
count=0;
}
newNode.next=null;
r.next=newNode;
r=newNode;
i++;
p=p.next;
q=q.next;
}
while (i<length_l1){
ListNode newNode;
if (p.val+count>=10){
newNode=new ListNode( (p.val+count-10));
count=1;
}else {
newNode=new ListNode(p.val+count);
count=0;
}
newNode.next=null;
r.next=newNode;
r=newNode;
i++;
p=p.next;
}
while (i<length_l2){
ListNode newNode;
if (q.val+count>=10){
newNode=new ListNode( (q.val+count-10));
count=1;
}else {
newNode=new ListNode(q.val+count);
count=0;
}
newNode.next=null;
r.next=newNode;
r=newNode;
i++;
q=q.next;
}
if (count==1){
ListNode newNode=new ListNode( 1);
r.next=newNode;
newNode.next=null;
r=newNode;
}
return header.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
##审题
(1) 算法的入口参数是两个不带头节点的单链表(LeetCode题目没有说明不带头节点,由于我C语言习惯使用头节点的单链表,一直认为有头节点,导致一直提交失败,有点坑)
(2)数字在链表是逆序存储
(3)计算的结果在链表也是逆序存储
##解题思路
定义循环变量i对两个链表同时遍历,相加的结果存在新链表(使用尾插法创建),一定要注意进位,遍历完之后,把没有遍历完的链表继续遍历完。
##注意点
(1)在代码中,创建新的节点后再进位
(2)特别注意,如果两个数的和长度 大于 两个数的较长长度,再遍历完之后,新链表还需要再创建一个节点存放进位1