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

链表相加(二)

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) {
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        // write code here
        ListNode h1 = reverse(head1);
        ListNode h2 = reverse(head2);
        int carry = 0;
        ListNode res = new ListNode(-1);
        ListNode cur = res;
        while (h1 != null || h2 != null) {
            int v1 = h1 == null ? 0 : h1.val;
            int v2 = h2 == null ? 0 : h2.val;
            int sum = v1 + v2 + carry;
            cur.next = new ListNode(sum % 10);
            carry = sum / 10;
            cur = cur.next;
            h1 = h1 != null ? h1.next : null;
            h2 = h2 != null ? h2.next : null;
        }
        if (carry > 0) {
            cur.next = new ListNode(1);
            cur = cur.next;
        }
        return reverse(res.next);
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode pre = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
全部评论

相关推荐

06-18 15:03
门头沟学院 Java
至少实习看起来比去年好?问了下群里的同学和身边的同学,人均有offer。有的还有好几个大厂offer
菜鸟1973:上一年暑期也是人均大厂实习offer,结果秋招跟不招人一样,大部分都转正了
点赞 评论 收藏
分享
震撼沃玛一整年:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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