题解报告LeetCode#2:两数相加
思路:
代码:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNodel2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
int x, y, sum;
while (l1 != null || l2 != null) {
x = l1 == null ? 0 : l1.val;
y = l2 == null ? 0 : l2.val;
sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
}
if (carry == 1) {
cur.next = new ListNode(carry);
}
return pre.next;
}
}
题解报告LeetCode#445:两数相加Ⅱ
思路:利用辅助栈
代码:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode head = null;
while (!stack.isEmpty() || !stack.isEmpty() || carry != 0) {
int sum = carry;
sum += stack1.isEmpty() ? 0 : stack1.pop();
sum += stack2.isEmpty() ? 0 : stack2.pop();
ListNode node = new ListNode(sum % 10);
node.next = head;
head = node;
carry = sum / 10;
}
return head;
}
}