题解 | 链表相加(二)

链表相加(二)

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

import java.util.*;

public class Solution {
   
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        // 需要设置一个进位,查看是否需要进位,将进位后的结果(对10取模)加入新的链表节点
        if(head1 == null)
            return head2;
        if(head2 == null)
            return head1;
        head1 = ReverseList(head1);
        head2 = ReverseList(head2);
        ListNode res = new ListNode(-1);
        ListNode head = res;
        int carry = 0;
        // 只要某个链表还有或者进位还有
        while(head1 != null || head2 != null || carry != 0){
            int val1 = head1 == null ? 0 : head1.val;
            int val2 = head2 == null ? 0 : head2.val;
            int temp = val1 + val2 + carry;
            // 获取进位
            carry = temp / 10;
            temp %= 10;
            head.next = new ListNode(temp);
            head = head.next;
            if(head1 != null){
                head1 = head1.next;
            }
            if(head2 != null){
                head2 = head2.next;
            }
        }
        return ReverseList(res.next);
    }

    //反转链表
    public ListNode ReverseList(ListNode pHead) {
        if (pHead == null)
            return null;
        ListNode cur = pHead;
        ListNode pre = null;
        while (cur != null) {
            //断开链表,要记录后续一个
            ListNode temp = cur.next;
            //当前的next指向前一个
            cur.next = pre;
            //前一个更新为当前
            pre = cur;
            //当前更新为刚刚记录的后一个
            cur = temp;
        }
        return pre;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-24 13:40
点赞 评论 收藏
分享
07-24 19:01
门头沟学院 Java
后天笔试,又要开始做题了
Sairus:明天10:00笔试
投递京东等公司10个岗位
点赞 评论 收藏
分享
07-20 12:08
已编辑
江南大学 图像识别
机械牛马勇闯秋招:把校园经历里面做过的项目,大作业,课设,毕设啥的,扩写,写成具体的项目经历,自我评价缩写别占篇幅,不然这简历真没东西,初筛都过不了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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