71 lines
1.7 KiB
Java
71 lines
1.7 KiB
Java
/*
|
|
* @lc app=leetcode id=445 lang=java
|
|
*
|
|
* [445] Add Two Numbers II
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* 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) {
|
|
l1 = reverse(l1);
|
|
l2 = reverse(l2);
|
|
return reverse(addByLittleEnd(l1, l2));
|
|
}
|
|
|
|
private ListNode addByLittleEnd(ListNode l1, ListNode l2) {
|
|
ListNode dummy = new ListNode(0), tail = dummy;
|
|
dummy.next = null;
|
|
boolean flow = false;
|
|
while(l1 != null || l2 != null) {
|
|
int v1 = l1==null?0:l1.val;
|
|
int v2 = l2==null?0:l2.val;
|
|
int v = v1 + v2 + (flow?1:0);
|
|
flow = v>=10;
|
|
ListNode tmp = new ListNode(v%10, null);
|
|
tail.next = tmp;
|
|
tail = tail.next;
|
|
tail.next = null;
|
|
if(l1 != null) {
|
|
l1 = l1.next;
|
|
}
|
|
if(l2 != null) {
|
|
l2 = l2.next;
|
|
}
|
|
}
|
|
if(flow) {
|
|
ListNode tmp = new ListNode(1, null);
|
|
tail.next = tmp;
|
|
tail = tail.next;
|
|
tail.next = null;
|
|
}
|
|
return dummy.next;
|
|
}
|
|
|
|
private ListNode reverse(ListNode l) {
|
|
if(l == null) {
|
|
return l;
|
|
}
|
|
ListNode dummy = new ListNode(0), tmp;
|
|
dummy.next = null;
|
|
while(l != null) {
|
|
tmp = l.next;
|
|
l.next = dummy.next;
|
|
dummy.next = l;
|
|
l = tmp;
|
|
}
|
|
return dummy.next;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|