关于leetcode个人解题总结:刷题14两数相加-II

15次阅读

共计 718 个字符,预计需要花费 2 分钟才能阅读完成。

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;
    }
}
正文完
 0