剣指-一方向チェーンテーブルが環状構造を形成しているかどうかを判断する
テーマ:一方向チェーンテーブルが環状構造を形成しているかどうかを判断する.構想:2つのポインタを定義し、同時にチェーンテーブルの頭部から出発し、1つのポインタは1回1歩、もう1つのポインタは1回2歩歩く.速いポインタが遅いポインタに追いつくと、チェーンテーブルはリングチェーンテーブルになります.チェーンテーブルの尾まで速く歩いても最初のポインタに追いつかないと、チェーンテーブルはリングチェーンテーブルではありません.
private static class Node {
int value;
Node next;
}
static boolean isRing(Node head) {
if (head == null) {
return false;
}
Node pre = head;
Node rear = head;
while (rear.next != null) {
if (rear.next.next != null) {
rear = rear.next.next;
} else {
return false;
}
if (rear.next.next == pre) {
return true;
}
pre = pre.next;
}
return false;
}
public static void main(String[] args) {
Node head = new Node();
head.value = 1;
addTail(head, 2);
addTail(head, 3);
addTail(head, 4);
addTail(head, 5);
addTail(head, 6);
addTail(head, 7);
addTail(head, 8);
Node _9 = addTail(head, 9);
addTail(head, 10);
addTail(head, 11);
addTail(head, 12);
addTail(head, 13);
addTail(head, 14);
Node tail = addTail(head, 15);
tail.next = _9;
System.out.println(isRing(head));
}
private static Node addTail(Node head, int value) {
Node node = new Node();
node.value = value;
if (head != null) {
Node tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = node;
}
return node;
}