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; }}