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

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        Stack<ListNode>  st1 = new Stack<>();
        Stack<ListNode> st2 = new Stack<>();
        ListNode start = new ListNode(-1);
        while (head1 != null) {
            st1.add(head1);
            head1 = head1.next;
        }
        while (head2 != null) {
            st2.add(head2);
            head2 = head2.next;
        }
        int jinwei = 0;
        while (!st1.isEmpty() && !st2.isEmpty()) {
            int nodeVal = st1.pop().val + st2.pop().val + jinwei;
            jinwei = nodeVal / 10;
            ListNode temp = new ListNode(nodeVal % 10);
            temp.next = start.next;
            start.next = temp;
        }
        while (!st1.isEmpty()) {
            int nodeVal = st1.pop().val + jinwei;
            jinwei = nodeVal / 10;
            ListNode temp = new ListNode(nodeVal % 10);
            temp.next = start.next;
            start.next = temp;
        }
        while (!st2.isEmpty()) {
            int nodeVal = st2.pop().val + jinwei;
            jinwei = nodeVal / 10;
            ListNode temp = new ListNode(nodeVal % 10);
            temp.next = start.next;
            start.next = temp;

        }
        return start.next;
    }
}

我是利用了栈。如果没其他性能要求的话,这样还是最稳妥的。

全部评论

相关推荐

点赞 评论 收藏
分享
昨天 16:00
门头沟学院 Java
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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