题目:给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表;
例如:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出: 7 -> 8 -> 0 -> 7
注意链表的顺序,如果链表是倒序,可以直接进行相加,可以考虑先把链表倒置后再进行相加操作,但是我们考虑一下栈的性质,先进后出,把链表都入栈,再弹栈进行操作会简单得多
直接上代码:
public class NumberPlus {
private class ListNode{
private int val;
private ListNode next;
public ListNode(int x) {
val = x;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
}
ListNode targetHead = null;
int carry = 0;
//注意carry != 0不能漏掉,否则5+5=0
while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
int sum = 0;
if (!s1.isEmpty()) {
sum = sum + s1.pop();
}
if (!s2.isEmpty()) {
sum = sum + s2.pop();
}
sum = sum + carry;
int value = sum%10;
carry = sum / 10;
ListNode listNode = new ListNode(value);
listNode.next = targetHead;
targetHead = listNode;
}
return targetHead;
}
}