445. 两数相加 II

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


最高位变成了头结点,这样就需要从后向前遍历。借用栈的性质

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        Stack<ListNode> stack1 = putStack(l1);
        Stack<ListNode> stack2 = putStack(l2);
        ListNode head = null;
        int carry = 0;
        while(!stack1.isEmpty() || !stack2.isEmpty()) {
            int num1 = stack1.isEmpty() ? 0 : stack1.pop().val;
            int num2 = stack2.isEmpty() ? 0 : stack2.pop().val;

            int sum = num1 + num2 + carry;
            ListNode cur = new ListNode(sum %10);
            cur.next = head;
            head = cur;
            carry = sum / 10;
        }

        if(carry != 0) {
            ListNode cur = new ListNode(carry);
            cur.next = head;
            head = cur;
        }
        return head;

    }

    
    // 由于最高位位于开始,那么就要用到stack了

    public Stack<ListNode> putStack(ListNode list) {

        Stack<ListNode> stack = new Stack<>();
        while(list != null) {
            stack.push(list);
            list = list.next;
        }
        return stack;

    }
posted @ 2022-02-25 16:10  一颗青菜  阅读(8)  评论(0)    收藏  举报