题解 | 链表相加(二)

链表相加(二)

https://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) {
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        Stack<ListNode> result = new Stack<>();

        while (head1 != null) {
            stack1.push(head1);
            head1 = head1.next;
        }

        while (head2 != null) {
            stack2.push(head2);
            head2 = head2.next;
        }

        boolean temp = false;

        while (!stack1.empty() || !stack2.empty()) {
            ListNode node1 =  stack1.empty() ? new ListNode(0) : stack1.pop();
            ListNode node2 =  stack2.empty() ? new ListNode(0) : stack2.pop();
            int tempSum = node1.val + node2.val + (temp ? 1 : 0);
            temp = tempSum >= 10;
            result.push(new ListNode(tempSum % 10));
        }
        if (temp) {
            result.push(new ListNode(1));
        }
        ListNode res = new ListNode(0);
        ListNode head = res;
        while (!result.empty()) {
            head.next = result.pop();
            head = head.next;
        }
        return res.next;
    }


}

全部评论

相关推荐

09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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