题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

public ListNode addInList(ListNode head1, ListNode head2) {
        //参数校验
        if (head1 == null && head2 == null) return null;
        if (head1 == null) return head2;
        if (head2 == null) return head1;
        //创建两个栈,利用栈的性质进行计算
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        Stack<Integer> resultStack = new Stack<>();
        //将两个链表的数据存入两个栈中
        while (head1 != null) {
            stack1.add(head1.val);
            head1 = head1.next;
        }
        while (head2 != null) {
            stack2.add(head2.val);
            head2 = head2.next;
        }
        int carry = 0;
        int value = 0;
        //取出栈内的元素进行计算
        while (!stack1.isEmpty() || !stack2.isEmpty()) {
            if (stack1.isEmpty()) {
                int sum = stack2.pop() + carry;
                value = sum % 10;
                carry = sum / 10;
                resultStack.add(value);
                continue;
            }
            if (stack2.isEmpty()) {
                int sum = stack1.pop() + carry;
                value = sum % 10;
                carry = sum / 10;
                resultStack.add(value);
                continue;
            }
            int sum = stack1.pop() + stack2.pop() + carry;
            value = sum % 10;
            carry = sum / 10;
            resultStack.add(value);
        }
        if(carry != 0) resultStack.add(carry);
        //去除resultStack内的元素存入ListNode
        ListNode head = new ListNode(resultStack.pop());
        ListNode result = head;
        while(!resultStack.isEmpty()){
            head.next = new ListNode(resultStack.pop());
            head = head.next;
        }
        return result;
}

解题思路:思路相对比较简单,利用栈内元素先进先出,后进后出的特性

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务