赞
踩
- public class Demo {
-
- public static void main(String[] args) {
- // 链表中环的检测
- Node node = getNode(10, true);
- boolean checkRing = checkRing(node);
- System.out.println(checkRing);
- }
-
- // 环检测
- private static boolean checkRing(Node node) {
- Node fast = node;
- Node show = node;
- while (fast != null && fast.next != null) {
- fast = fast.next.next;
- show = show.next;
- if (fast == show) {
- return true;
- }
- }
- return false;
- }
-
- // 获取普通链表
- private static Node getNode(Integer n, boolean ring) {
- Node head = null;
- Node node = null;
- for (int i = 1; i <= n; i++) {
- Node next = new Node(i);
- if (node == null) {
- node = next;
- head = next;
- } else {
- node.next = next;
- node = next;
- }
- }
- // 是否造环
- if (ring) {
- node.next = head;
- }
- return head;
- }
-
- static class Node {
- public Node next;
- public Integer value;
-
- public Node(Integer value) {
- this.value = value;
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。