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

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList(ListNode head1, ListNode head2) {
        // write code here
        if (head1 == null || head2 == null) {
            return head1 == null ? head2 : head1;
        }
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null) {
            stack1.push(cur1);
            cur1 = cur1.next;
        }
        while (cur2 != null) {
            stack2.push(cur2);
            cur2 = cur2.next;
        }
        
        cur1 = stack1.pop();
        cur2 = stack2.pop();
        
        int carry = (cur1.val + cur2.val) / 10;
        int val = (cur1.val + cur2.val) % 10;
        ListNode head = new ListNode(val);
        while (!stack1.isEmpty() || !stack2.isEmpty()) {
            val = carry;
            if (!stack1.isEmpty()) {
                val += stack1.pop().val;
            }
            if (!stack2.isEmpty()) {
                val += stack2.pop().val;
            }
            carry = val / 10;
            val = val % 10;
            ListNode cur = new ListNode(val);
            cur.next = head;
            head = cur;
        }
        if (carry != 0) {
            ListNode cur = new ListNode(carry);
            cur.next = head;
            head = cur;
        }
        return head;
    }
    
}

全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务