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

链表相加(二)

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;
    }
全部评论

相关推荐

Noel_:中石油是这样的 哥们侥幸混进免笔试名单 一看给我吓尿了
点赞 评论 收藏
分享
10-15 15:00
潍坊学院 golang
跨考小白:这又不是官方
投递拼多多集团-PDD等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务