问题描述
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
总体思路:两个链表相加,需要考虑,
- 进位
- 两个链表长度不同、相同
- 1和2叠加到一起
重点
由于我是将第一条链表的基础上进行操作,所以涉及到链表1最后为null且需要进位的情况,这时候可不能仅仅将l1赋值为新节点,所以需要有辅助节点记录最后一个非null节点
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int temp = -1;
int add = 0;
/**这里用一个辅助节点的用意就在于,由于我们是拿1的空间做的新 链表,
存在最后l1.next为null的情况,在处理进位的时候不能仅仅将l1被赋值为新节点(java的值传递),所以我们不能将希望全放在l1上,
这就是pre节点的作用,记录最后一个非null节点**/
ListNode pre = new ListNode(0);
pre.next = l1;
ListNode result = pre;
while (l1 != null && l2 != null) {
temp = l1.val + l2.val + add;
add = temp / 10;
temp = temp%10;
l1.val = temp;
pre = l1;
l1 = l1.next;
l2 = l2.next;
}
if (l1 == null && l2 != null) {//2比1长
pre.next = l2;
while (add != 0 && l2 != null) {
temp = l2.val + add;
l2.val = temp % 10;
add = temp / 10;
pre = l2;
l2 = l2.next;
}
if(add != 0){//2最后还有一个进位需要处理
ListNode last = new ListNode(add);
pre.next = last;
last.next = null;
}
return result.next;
}else if (l2 == null && l1 != null) {//1比2长
while (add != 0 && l1 != null) {
temp = l1.val + add;
l1.val = temp % 10;
add = temp / 10;
pre = l1;
l1 = l1.next;
}
if(add != 0){//1最后还有一个进位需要处理
ListNode last = new ListNode(add);
pre.next = last;
last.next = null;
}
return result.next;
}else if (l1 == null && l2 == null){
if (add != 0) {
ListNode last = new ListNode(add);
pre.next = last;
last.next = null;
return result.next;
}else {
return result.next;
}
}
return result.next;
}
当然最后还是挑一个简洁好看的代码看看,只不过一般要么就是另开空间要么就是两条链都会遍历完 来自LeetCode,id:Ferrad
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode p1 = l1, p2 = l2, p = head;
int c = 0;
while(p1!=null || p2!=null || c==1){
int add1 = (p1==null ? 0 : p1.val);
int add2 = (p2==null ? 0 : p2.val);
int k = add1 + add2 + c;
c = k/10;
p.next = new ListNode(k%10);
p = p.next;
if(p1!=null){p1 = p1.next;}
if(p2!=null){p2 = p2.next;}
}
return head.next;
}