/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode last = null;
ListNode current = null;
ListNode result = null;
while(l1!=null && l2!=null){
if(l1.val+l2.val + carry >= 10){
current = new ListNode(l1.val+l2.val+carry - 10);
carry = 1;
}else{
current = new ListNode(l1.val+l2.val+carry);
carry = 0;
}
if(last == null){
result = current;
}else{
last.next = current;
}
l1 = l1.next;
l2 = l2.next;
if(l1 == null&&l2==null &&carry == 1){
current.next = new ListNode(1);
break;
}
last = current;
}
while(l1!=null){
if(l1.val + carry >= 10){
current = new ListNode(l1.val +carry - 10);
carry = 1;
}else{
current = new ListNode(l1.val + carry);
carry = 0;
}
last.next = current;
last = current;
l1 = l1.next;
if(l1 == null && carry == 1){
current.next = new ListNode(1);
break;
}
}
while(l2!=null){
if(l2.val + carry >= 10){
current = new ListNode(l2.val +carry - 10);
carry = 1;
}else{
current = new ListNode(l2.val + carry);
carry = 0;
}
last.next = current;
last = current;
l2 = l2.next;
if(l2 == null && carry == 1){
current.next = new ListNode(1);
break;
}
}
return result;
}
}
Optimization~~~
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10; //goode coding to present the addtiong digit
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
}
网友评论