题解 | 链表相加(二)

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        //翻转链表1
        ListNode node1 = reverseList(head1);
        //翻转链表2
        ListNode node2 = reverseList(head2);
        //结果链表
        ListNode resultNode = node1;
        //上一个节点
        ListNode preNode = node1;
        //是否进位
        int carry = 0;

        //从后往前加
        while (node1 != null && node2 != null) {
            int sum = node1.val + node2.val + carry;
            node1.val = sum % 10;
            carry = sum / 10;
            preNode = node1;
            node1 = node1.next;
            node2 = node2.next;
        }

        //链表长度不一致,公共长度加完后,需要接上
        if (node2 != null) {
            assert preNode != null;
            preNode.next = node2;
        }
        assert preNode != null;
        //当前节点
        ListNode currentNode = preNode.next;
        //如果进位了,需要一直往前加
        while (carry == 1 && currentNode != null) {
            int sum = currentNode.val + carry;
            currentNode.val = sum % 10;
            carry = sum / 10;
            preNode = currentNode;
            currentNode = currentNode.next;
        }
        //走到了最后一位,还进位了,需要新增一个节点
        if (carry == 1) {
            preNode.next = new ListNode(carry);
        }
        //把链表反转就是答案
        return reverseList(resultNode);
    }

    public static ListNode reverseList(ListNode head) {
        if (head != null && head.next != null && head.next.next != null) {
            ListNode preNode = head;
            ListNode current = head.next;
            ListNode nextNode;
            //最开始的头节点指向空
            preNode.next = null;
            while (current != null) {
                //先获取下一个节点
                nextNode = current.next;
                //当前节点指向上一个节点
                current.next = preNode;
                //上一个节点赋值为当前节点
                preNode = current;
                //当前节点往后走一步
                current = nextNode;
            }
            return preNode;
        } else if (head != null && head.next != null) {
            ListNode nextNode = head.next;
            head.next = null;
            nextNode.next = head;
            return nextNode;
        } else {
            return head;
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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