@不了解前尘往事的Reader,烦请阅读——《判断单链表是否有环的算法》
不过我们这里不考虑带环单链表,且无环单链表相交也只是相交一次,不穿过,这是一种不算复杂的情况吧。
这里只说能想到的且比较可行的算法吧。
把两个链表的结点依次打入HashSet,打入前判重,如果有重,既然不是有环,那就是相交了。
两个链表都从头结点开始,一直跑到尾结点(事先未曾保存),看看尾结点一样不一样。
这思路也有些暴力,回头想想怎么去优化一些,先针对这个思路给出代码吧。
public class Main {
private static class Node<T> {
T element;
Node<T> next;
Node(T element) {
this.element = element;
}
}
private static class LinkedList<T> {
Node<T> first;
}
public static void main(String[] args) {
Node<Integer> node1 = new Node<>(1);
Node<Integer> node2 = new Node<>(2);
Node<Integer> node3 = new Node<>(3);
Node<Integer> node4 = new Node<>(4);
Node<Integer> node5 = new Node<>(5);
Node<Integer> node6 = new Node<>(6);
Node<Integer> node7 = new Node<>(7);
Node<Integer> node8 = new Node<>(8);
Node<Integer> node9 = new Node<>(9);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
LinkedList<Integer> list1 = new LinkedList<>();
list1.first = node1;
node6.next = node7;
node7.next = node8;
node8.next = node9;
node9.next = node4;
LinkedList<Integer> list2 = new LinkedList<>();
list2.first = node6;
Node<Integer> rear1 = list1.first;
Node<Integer> rear2 = list2.first;
while (rear1.next != null) {
rear1 = rear1.next;
}
while (rear2.next != null) {
rear2 = rear2.next;
}
System.out.println("两个链表是否相交:" + (rear1 == rear2));
}
}