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

链表相加(二)

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
        if (head1 == null) return head2;
        if (head2 == null) return head1;
        Stack<ListNode> st1 = new Stack<> ();
        ListNode tmp1 = head1;
        while (tmp1 != null) {
            st1.push(tmp1);
            tmp1 = tmp1.next;
        }
        Stack<ListNode> st2 = new Stack<> ();
        ListNode tmp2 = head2;
        while (tmp2 != null) {
            st2.push(tmp2);
            tmp2 = tmp2.next;
        }
        ListNode res  = new ListNode(0);
        int n, m, s = 0, b = 0;
        while (!st1.isEmpty() || !st2.isEmpty()) {
            n = st1.isEmpty() ? 0 : st1.pop().val;
            m = st2.isEmpty() ? 0 : st2.pop().val;
            s = n + m + b;
            b = s >= 10 ? 1 : 0;
            ListNode newNode = new ListNode(s % 10);
            newNode.next = res.next;
            res.next = newNode;
        }
        if (b > 0) {
            ListNode newNode = new ListNode(b);
            newNode.next = res.next;
            res.next = newNode;
        }
        return res.next;
    }
}

全部评论

相关推荐

头像
05-12 09:14
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务