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

链表相加(二)

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

public static ListNode addInList(ListNode head1, ListNode head2) { // write code here Stack stack1 = new Stack<>(); while (head1 != null) { stack1.push(head1.val); head1 = head1.next; } Stack stack2 = new Stack<>(); while (head2 != null) { stack2.push(head2.val); head2 = head2.next; }

        ListNode newNode = new ListNode(-1);
        ListNode nowNode = newNode;
        int yu = 0;
        while (stack1.size() > 0 || stack2.size() > 0) {
            int temp = yu;
            if (stack1.size() > 0) {
                temp += stack1.pop();
            }
            if (stack2.size() > 0) {
                temp += stack2.pop();
            }
            if (temp >= 10) {
                yu = 1;
                temp = temp % 10;
            } else {
                yu = 0;
            }
            nowNode.next = new ListNode(temp);
            nowNode = nowNode.next;
        }
        if (yu == 1) {
            nowNode.next = new ListNode(1);
        }
        nowNode = reverse(newNode.next);
        return nowNode;

    }

    private static ListNode reverse(ListNode now) {
        ListNode pre = null;
        while (now != null) {
            ListNode next = now.next;
            now.next = pre;
            pre = now;
            now = next;
        }
        return pre;
    }
全部评论

相关推荐

dongsheng66:如果想进大厂的话,在校经历没必要占这么大篇幅,可以把专业技能单独放一个专栏写,可以加个项目经历
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务