Leetcode:445. 两数相加 II
解法:加法运算从低位开始运算,但低位数字在链表的末尾,因此可以借助栈的后入先出特性来解决。首先把两链表中的元素分别压入两个栈st1和st2,然后弹出两栈的栈顶元素和进位三数相加得到和sum(进位carry初始值为0),取和sum%10作为低位数,用链表节点保存,从头插入链表开头,取carry=sum/10作为下一个高位数的进位。只要两栈任意一个不为空或者carry大于0,都进行位数加法操作,并把保存结果得节点插入到开头。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> st1 = new Stack<>();
Stack<Integer> st2 = new Stack<>();
ListNode pre = new ListNode(-1,null);
while(l1 != null){
st1.push(l1.val);
l1 = l1.next;
}
while(l2 != null){
st2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
while(carry > 0 || !st1.isEmpty() || !st2.isEmpty()){
int sum = 0;
sum += carry;
sum += st1.isEmpty()?0 : st1.pop();
sum += st2.isEmpty()?0 : st2.pop();
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
node.next = pre.next;
pre.next = node;
}
return pre.next;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。