栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何判断两个单链表相交的第一个交点

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何判断两个单链表相交的第一个交点

思路分析:
首先遍历获得两个单链表得到它们的长度(长度分别记为 len1 和 len2),定义 longNode 指针指 向长度较长的单链表的首节点,定义 shortNode 指针指向长度较短的单链表的首节点,然后让 longNode 指针往后走 Math.abs(len1-len2)步。接着,定义一个循环,每次让 longNode 指针和 shortNode 指针往后移动一步,当 longNode 指针和 shortNode 指针指向同一个节点时,则停止循环。此时, longNode 和 shortNode 指向的节点,就是两个单链表相交的第一个交点。

节点类
@Data
public class Node {
    
    private Object data;
    
    private Node next;

    public Node(Object data) {
        this.data = data;
    }

    public Node(Object data, Node next) {
        this.data = data;
        this.next = next;
    }
}

实现类
package day04;


public class Test08 {
    public static void main(String[] args) {
        //定义2个单链表
        Node lastNode = new Node(77);
        Node node6 = new Node(66,lastNode);
        Node node3 = new Node(33,node6);
        Node node2 = new Node(22,node3);
        Node head1 = new Node(11,node2);
        Node node5 = new Node(55,node6);
        Node head2 = new Node(44,node5);
        Node commonNode = getFirstCommonNode(head1, head2);
        System.out.println("两个单链表相交的第一个交点:" + commonNode.getData());
    }

    
    public static Node getFirstCommonNode(Node head1,Node head2){
        //处理head1或者head2 为null的情况
        if (head1 == null || head2 ==null)
            return null;
        //获得以head1为首节点的单链表长度
        int length1 = getLength(head1);
        //获得以head2为首节点的单链表长度
        int length2 = getLength(head2);
        //定义longNode指针,用于指向长度较长单链表的首节点
        Node longNode = length1 > length2 ? head1 : head2;
        //定义shortNode指针,用于指向长度较短单链表的首节点
        Node shortNode = length1 > length2 ? head2 : head1;
        //让longNode指针往后移动Math.abs(length1 - length2)
        for (int i = 0; i < Math.abs(length1 - length2); i++)
            longNode = longNode.getNext();
        //定义一个循环,每次让longNode和shortNode往后移动一次
        while (longNode !=shortNode){
            longNode = longNode.getNext();
            shortNode = shortNode.getNext();
        }
        //执行到这里返回两个单链表相交的节点
        return longNode;
    }

    
    public static int getLength(Node headNode){
        //定义一个变量存储单链表的长度
        int length = 0;
        //定义一个循环,用于实现单链表的遍历操作
        Node tempNode = headNode;
        while (tempNode != null){
            tempNode = tempNode.getNext();
            //更新length的值
            length++;
        }
        //返回单链表的长度
        return length;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/877307.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号