判断两个单链表是否相交
思路:之前想到的只是两个无环链表,但没想到有环链表也需要考虑。故写随笔记录下来。
条件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:一个有环一个没环
必定不相交