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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| public static Node getloopNode(Node head){ if(head.next == null || head.next.next == null || head.next.next == null){ return null; }
Node node1 = head.next; Node node2 = head.next.next;
while(node1 != node2){ if(node2.next == null || node2.next.next == null){ return null; }
node2 = node2.next.next; node1 = node1.next; }
node2 = head;
while(node1 != node2){ node1 = node1.next; node2 = node2.next; } return node1; }
public static Node noLoop(Node head1,Node head2){ if(head1 == null || head2.next == null){ return null; }
Node cur1 = head1; Node cur2 = head2;
int n = 0;
while(cur1.next != null){ n++; cur1 = cur1.next; }
while(cur2.next != null){ n--; cur2 = cur2.next; }
if(cur1 != cur2){ return null; }
cur1 = n > 0 ? head1 : head2; cur2 = cur1 == head1 ? head2 :head1;
n = Math.abs(n);
while(n != 0){ n--; cur1 = cur1.next; }
while(cur1 != cur2){ cur1 = cur1.next; cur2 = cur2.next; }
return cur1; }
public static Node BothLoop(Node head1,Node loopNode1,Node head2,Node loopNode2){ Node cur1 = null; Node cur2 = null;
if(loopNode1 == loopNode2){ cur1 = head1; cur2 = head2; int n = 0;
while (cur1 != loopNode1){ n++; cur1 = cur1.next; }
while (cur2 != loopNode1){ n--; cur2 = cur2.next; }
cur1 = n > 0 ? head1 :head2; cur2 = cur1 == head1 ? head2 : head1; n = Math.abs(n); while (n != 0) { n--; cur1 = cur1.next; } while(cur1 != cur2){ cur1 = cur1.next; cur2 = cur2.next; }
return cur1; }else{ cur1 = loopNode1.next; while(cur1 != loopNode1){ if(cur1 == loopNode2){ return loopNode1; } cur1 = cur1.next; } return null; } }
|