题解 | 链表相加(二)

链表相加(二)

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:35
点赞 评论 收藏
分享
07-23 14:04
东北大学 C++
既然这样,为什么不点击就送呢
牛马88号:因为你合适。但有很多笔试就挂了、通过了再排序的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-15 22:48
牛马人的牛马人生:建议就是把北邮几个字放大就行了。北邮本硕按理来说完全不用担心啊
点赞 评论 收藏
分享
码砖:求职岗位要突出,一眼就能看到,教育背景放到最后,学校经历没那么重要,项目要重点突出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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