当前位置:   article > 正文

数据结构与算法(二)——链表中环的检测

链表中环的检测

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 链表中环的检测
  4. Node node = getNode(10, true);
  5. boolean checkRing = checkRing(node);
  6. System.out.println(checkRing);
  7. }
  8. // 环检测
  9. private static boolean checkRing(Node node) {
  10. Node fast = node;
  11. Node show = node;
  12. while (fast != null && fast.next != null) {
  13. fast = fast.next.next;
  14. show = show.next;
  15. if (fast == show) {
  16. return true;
  17. }
  18. }
  19. return false;
  20. }
  21. // 获取普通链表
  22. private static Node getNode(Integer n, boolean ring) {
  23. Node head = null;
  24. Node node = null;
  25. for (int i = 1; i <= n; i++) {
  26. Node next = new Node(i);
  27. if (node == null) {
  28. node = next;
  29. head = next;
  30. } else {
  31. node.next = next;
  32. node = next;
  33. }
  34. }
  35. // 是否造环
  36. if (ring) {
  37. node.next = head;
  38. }
  39. return head;
  40. }
  41. static class Node {
  42. public Node next;
  43. public Integer value;
  44. public Node(Integer value) {
  45. this.value = value;
  46. }
  47. }
  48. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/64524?site
推荐阅读
相关标签
  

闽ICP备14008679号