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

链表相加(二)

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

/**
 * @author Lu.F
 * @version 1.0
 * @date 2022/10/8 21:44
 */
public class Solution3 {
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        // 判断是否为空
        if (head1 == null){
            return head2;
        }

        if (head2 == null){
            return head1;
        }

        // 反转链表
        ListNode pHead1 = reverseList(head1);
        ListNode pHead2 = reverseList(head2);

        ListNode pHead = new ListNode(-1);

        ListNode head = pHead;
        // 记录进位
        int temp = 0;

        while (pHead1 != null || pHead2 != null){
            // 记录进位(加数+加数+进位)
            int val = temp;
            if (pHead1 != null){
                val += pHead1.val;
                pHead1 = pHead1.next;
            }

            if (pHead2 != null){
                val += pHead2.val;
                pHead2 = pHead2.next;
            }

            // 获取进位
            temp = val/10;

            // 获取个位
            pHead.next = new ListNode(val%10);

            // 继续指向下个
            pHead = pHead.next;
        }

        // 如果进位大于0则增加一个
        if (temp > 0){
            pHead.next = new ListNode(temp);
        }

        // 将结果逆转返回最终答案
        return reverseList(head.next);

    }

    /**
     * 反转链表
     * @param head
     * @return
     */
    private ListNode reverseList(ListNode head){
        // 判断非空
        if (head == null){
            return null;
        }
        // 记录当前指针
        ListNode cur = head;
        // 记录前一个指针
        ListNode node = null;
        while (cur != null){
            ListNode tail = cur.next;
            cur.next = node;
            node = cur;
            cur = tail;
        }

        return node;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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