题目:给定两个非空的链表,存储的是两个非负整数,以逆序的形式存储这两个数的每一个元素,求这两个数之和,并且也以逆序返回
例子:342+465的存储形式为
(2->4->3)和 (5->6->4)
返回结果为:(7->0->8)思路:首先这一题不需要判空。
这一题只需要考虑两个问题:- 进位
- 链表长度不同
对于进位:只需要用一个变量carry来记录,但不要忘了两个链表最尾部进位问题(即最后carry不为0的话,需要再多加一个结点)
对于链表长度:
* 或者 两个指针同时移动,一旦有指针为空,退出当前循环;之后对不为空的链表进行处理 * 递归补值为0的节点
代码一:(指针同时移动,某个链表为空,则退出while循环)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode newHead = new ListNode(0);
ListNode node = newHead;
int carry = 0;
while(l1 != null && l2 != null){
int value = l1.val + l2.val + carry;
carry = value/10;
node.next = new ListNode(value%10);
node = node.next;
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null){
int value = carry + l1.val;
carry = value/10;
node.next = new ListNode(value%10);
node = node.next;
l1 = l1.next;
}
while(l2 != null){
int value = carry + l2.val;
carry = value/10;
node.next = new ListNode(value%10);
node = node.next;
l2 = l2.next;
}
if(carry != 0){
node.next = new ListNode(carry);
}
return newHead.next;
}
}
- 代码二:(当其中一个链表不为空时,为空的链表加上值为0的节点)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
return helper(l1, l2, carry);
}
private ListNode helper(ListNode l1, ListNode l2, int carry){
if(l1 == null && l2 == null){
if(carry != 0){
ListNode curr = new ListNode(carry);
return curr;
}else{
return null;
}
}
if(l1 == null && l2 != null){
l1 = new ListNode(0);
}
if(l2 == null && l1 != null){
l2 = new ListNode(0);
}
int value = l1.val + l2.val + carry;
carry = value/10;
ListNode curr = new ListNode(value%10);
curr.next = helper(l1.next, l2.next, carry);
return curr;
}
}