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

链表相加(二)

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;
    }
}

全部评论

相关推荐

26牛牛不会梦到感谢信:羡慕离职了还能吃吗现在就赶回去
点赞 评论 收藏
分享
2024-12-23 11:36
中南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务