码迷,mamicode.com
首页 > 其他好文 > 详细

判断两个单链表是否相交

时间:2017-10-12 10:39:42      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:code   一个   ati   return   sys   als   inter   val   print   

思路:之前想到的只是两个无环链表,但没想到有环链表也需要考虑。故写随笔记录下来。

 

条件1:两个无环链表

class Node {
    int val;
    Node next = null;

    Node(int val) {
        this.val = val;
    }
}

public class Main {
    public static void main(String[] args) {
        Node node11 = new Node(11);
        Node node12 = new Node(12);
        Node node13 = new Node(13);
        Node node14 = new Node(14);
        Node node15 = new Node(15);
        Node node16 = new Node(16);
        Node node21 = new Node(21);
        Node node22 = new Node(22);
        Node node23 = new Node(23);
        Node node24 = new Node(24);

        node11.next = node12;
        node12.next = node13;
        node13.next = node14;
        node14.next = node15;
        node15.next = node16;
        node21.next = node22;
        node22.next = node23;
        node23.next = node24;
        node24.next = node15;

        System.out.println(findIntersect(node11, node21));
    }

    public static boolean findIntersect(Node node1, Node node2) {
        while (node1.next != null) {
            node1 = node1.next;
        }
        while (node2.next != null) {
            node2 = node2.next;
        }

        if (node1 == node2) {
            return true;
        }
        return false;
    }
}

 

 

条件2:两个有环链表(待添加代码)

判断环入口是否相等,入口相等则必定相交;不相等则判断,A环入口是否在B环中,在则说明相交,反之不相交

 

条件3:一个有环一个没环

必定不相交

判断两个单链表是否相交

标签:code   一个   ati   return   sys   als   inter   val   print   

原文地址:http://www.cnblogs.com/Melinni/p/7654415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!