题解 | #两个链表生成相加链表#

import java.util.*;

public class Solution {
    public ListNode addInList (ListNode head1, ListNode head2) {
        ListNode h1 = reverse(head1), h2 = reverse(head2);
        ListNode dummy = new ListNode(-1);
        ListNode cursor = dummy;
        int carry = 0;
        while(h1 != null || h2 != null || carry != 0){
            int h1Val = h1 == null ? 0 : h1.val;
            int h2Val = h2 == null ? 0 : h2.val;
            int sum = h1Val + h2Val + carry;
            ListNode node = new ListNode(sum % 10);
            carry = sum / 10;
            cursor.next = node;
            cursor = node;
            if(h1 != null) h1 = h1.next;
            if(h2 != null) h2 = h2.next;
        }
        return reverse(dummy.next);
    }
    
    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode cur = head;
        ListNode temp = null;
        while(cur != null){
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
简历当中有水分算不算造假...
点赞 评论 收藏
分享
05-25 10:45
门头沟学院 Java
Frank_zhan...:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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