题目
如图所示,找出两个单链表的相交点,若没有返回null

最好不要使用其他的辅助的数据结构,降低空间复杂度
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Node { Node next; }
public class Main { public static void main(String[] args) { Node head1 = new Node(); head1.next = new Node(); head1.next.next = new Node(); head1.next.next.next = new Node(); System.out.println("设置相交点"+head1.next.next); Node head2 = new Node(); head2.next = head1.next.next; Node head3 = new Node(); head3.next = new Node(); head3.next.next = new Node(); head3.next.next.next = new Node(); Node res = findCrossNode(head1, head2); System.out.println("获取相交点"+res); res = findCrossNode(head1, head3); System.out.println("获取相交点"+res); }
private static Node findCrossNode(Node head1, Node head2) { Node n1 = head1; Node n2 = head2; int len1 = 1; int len2 = 1; while (n1.next != null) { n1 = n1.next; len1++; } while (n2.next != null) { n2 = n2.next; len2++; } if (n1 != n2) { return null; } else { Node longList = head1; Node shortList = head2; if (len1 < len2) { longList = head2; shortList = head1; } int dis = Math.abs(len1-len2); for (int i = 0; i < dis; i++) { longList = longList.next; } while (longList != null && shortList != null) { if (longList == shortList){ return longList; } longList = longList.next; shortList = shortList.next; } } return null; } }
|