Java教程

Java 程序检测链表中的循环

用于检测 LinkedList 中循环的 Java 程序

在这个例子中,我们将学习检测Java中LinkedList是否存在循环。
要理解此示例,您应该了解以下Java 编程主题:
Java LinkedList Java 方法

示例: 检测链表中的循环

class LinkedList {
  // create an object of Node class
  // represent the head of the linked list
  Node head;
  // static inner class
  static class Node {
    int value;
    // connect each node to next node
    Node next;
    Node(int d) {
      value = d;
      next = null;
    }
  }
  // check if loop is present
  public boolean checkLoop() {
    // create two references at start of LinkedList
    Node first = head;
    Node second = head;
    while(first != null && first.next !=null) {
      // move first reference by 2 nodes
      first = first.next.next;
      // move second reference by 1 node
      second = second.next;
      // if two references meet
      // then there is a loop
      if(first == second) {
        return true;
      }
    }
    return false;
  }
  public static void main(String[] args) {
    // create an object of LinkedList
    LinkedList linkedList = new LinkedList();
    // assign values to each linked list node
    linkedList.head = new Node(1);
    Node second = new Node(2);
    Node third = new Node(3);
    Node fourth = new Node(4);
    // connect each node of linked list to next node
    linkedList.head.next = second;
    second.next = third;
    third.next = fourth;
    // make loop in LinkedList
    fourth.next = second;
    // printing node-value
    System.out.print("LinkedList: ");
    int i = 1;
    while (i <= 4) {
      System.out.print(linkedList.head.value + " ");
      linkedList.head = linkedList.head.next;
      i++;
    }
    // call method to check loop
    boolean loop = linkedList.checkLoop();
    if(loop) {
      System.out.println("\nThere is a loop in LinkedList.");
    }
    else {
      System.out.println("\nThere is no loop in LinkedList.");
    }
  }
}
输出
LinkedList: 1 2 3 4 
There is a loop in LinkedList.
在上面的示例中,我们在 Java 中实现了 LinkedList。我们使用了Floyd 循环查找算法来检查 LinkedList中是否存在循环。
注意 checkLoop() 方法中的代码。这里,我们有两个名为 firstsecond 的变量,它们遍历 LinkedList 中的节点。
first-在单次迭代中遍历 2 个节点 second-在单次迭代中遍历 1 个节点
两个节点以不同的速度遍历。因此,如果 LinkedList 中存在循环,它们就会相遇。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4