题目描述
给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢?
示例:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912
正向存放 两个栈存储链表值
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
putData(stack1, l1);
putData(stack2, l2);
ListNode newNode = null;
ListNode head = null;
int carry = 0;
while(!stack1.isEmpty() || ! stack2.isEmpty() || carry != 0) {
int x = (stack1.isEmpty()) ? 0 : stack1.pop();
int y = (stack2.isEmpty()) ? 0 : stack2.pop();
int sum = x + y + carry;
carry = sum / 10;
//这时应该采用头插
newNode = new ListNode(sum % 10);
newNode.next = head;
head = newNode;
}
return head;
}
private static void putData(Stack<Integer> s1, ListNode l1) {
if (s1 == null) s1 = new Stack<>();
while(l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
}
}