题解 | 链表相加(二)

链表相加(二)

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

        head1 = getReverseNode(head1);


        head2 = getReverseNode(head2);



        ListNode dummy = new ListNode(-1);
        ListNode result = dummy;
        int temp = 0;
        while (head1 != null || head2 != null) {
            int val1 = 0;

            if (head1 != null) {
                val1 = head1.val;
            }

            int val2 = 0;

            if (head2 != null) {
                val2 = head2.val;
            }

            int val = 0;

            if (val1 + val2 + temp >= 10) {
                val = (val1 + val2 + temp) % 10;
                temp = (val1 + val2 + temp) / 10;
            } else {
                val = val1 + val2 + temp;
                temp = 0;
            }

            dummy.next = new ListNode(val);
            dummy = dummy.next;

            if(head1!=null){
              head1 = head1.next;
            }

            if(head2!=null){
              head2 = head2.next;
            }
        
        }

        if (temp != 0) {
            dummy.next = new ListNode(temp);

        }

        return getReverseNode(result.next);


    }

    public ListNode getReverseNode(ListNode node) {

        ListNode pre = null;
        while (node != null) {
            ListNode next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }
}

全部评论

相关推荐

UtopianYou...:这个简历排版真的不太行哦,去找免费的或者花点小钱,把排版弄整齐一点吧,看着舒服。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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