leetcode2-两数相加
作者:互联网
- 循环,每次相加都new一个新的节点
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;
int sum = 0;
while(l1 != null || l2 != null){
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
sum = n1+n2+sum/10;
if(head == null){
head = tail = new ListNode(sum % 10);
}else{
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
if(sum >= 10){
tail.next = new ListNode(1);
}
return head;
}
}
- 使用原有节点
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = 0;
ListNode head = null, tail = null;
while(l1 != null){
int n1 = l1.val;
int n2 = l2 != null ? l2.val : 0;
sum = n1+n2+sum/10;
l1.val = sum % 10;
if(head == null){
head = tail = l1;
}else{
tail.next = l1;
tail = tail.next;
}
l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
while(l2 != null){
sum = l2.val + sum / 10;
l2.val = sum % 10;
if(head == null){
head = tail = l2;
break;
}else{
tail.next = l2;
tail = tail.next;
}
l2 = l2.next;
}
if(sum >= 10){
tail.next = new ListNode(1);
}
return head;
}
}
标签:leetcode2,相加,next,tail,l2,l1,null,sum,两数 来源: https://www.cnblogs.com/xzh-yyds/p/16586053.html