思路与标准解法类似
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode();
ListNode curr = l3;
int temp = 0;
int val1 = 0;
int val2 = 0;
while (!(l1==null && l2==null)){
if (l1==null){
val1 = 0;
val2 = l2.val;
}
else if (l2 == null){
val1 = l1.val;
val2 = 0;
}
else{
val1 = l1.val;
val2 = l2.val;
}
temp += val1 + val2;
curr.val = temp %10;
temp = temp/10;
if (l1!=null) {l1 = l1.next;}
if (l2!=null) {l2 = l2.next;}
if (!(l1==null && l2==null && temp==0)){
curr.next = new ListNode();
curr = curr.next;
}
}
if (temp == 1) {curr.val = temp;}
return l3;
}
}
No comments:
Post a Comment