查找两个链表中第一个公共节点

题目
  • 查找两个链表中第一个公共节点
解法
  • 方法1
    class Node {
        // 指针
        Node next;
        // 数据
        int data;

        public Node(int data) {
            this.data = data;
        }
    }
    
   /**
     * 查询第一个公共节点
     *
     * @param nodeOne
     * @param nodeTwo
     * @return
     */
    public Node findFirstCommonNodeTwo(Node nodeOne, Node nodeTwo) {
        if (nodeOne == null || nodeTwo == null) return null;
        Node first = nodeOne;
        Node second = nodeTwo;

        while (first != second) {
            first = (first == null ? second : first.next);
            second = (second == null ? first : second.next);
        }
        return first;

    }
  • 方法二
  /**
     * 查找两个链表的第一个公共节点
     *
     * @param headOne
     * @param headTwo
     * @return
     */
    public Node findFirstCommonNode(Node headOne, Node headTwo) {
        int nodeOneLength = getLength(headOne);
        int nodeTwoLength = getLength(headTwo);

        // 长链表头节点
        Node nodeLong = headOne;
        // 短链表头结点
        Node nodeShort = headTwo;

        //  对比长度
        int diffLength;
        if (nodeOneLength > nodeTwoLength) {
            diffLength = nodeOneLength - nodeTwoLength;
        } else {
            nodeLong = headTwo;
            nodeShort = headOne;
            diffLength = nodeTwoLength - nodeOneLength;
        }

        // 移动头指针
        for (int i = 0; i < diffLength; i++) {
            nodeLong = nodeLong.next;
        }
        // 遍历比对
        while (nodeLong != null && nodeShort != null && nodeLong != nodeShort) {
            nodeLong = nodeLong.next;
            nodeShort = nodeShort.next;
        }
        return nodeLong;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值