Example #1
0
  public Question25() {
    list = new LinkedList();
    list.insert(1);
    list.insert(3);
    list.insert(5);
    list.insert(7);
    list.insert(8);
    list.insert(10);
    Node entry = list.root;
    for (int i = 0; i < 3; i++) entry = entry.next;

    Node last = list.root;
    while (last.next != null) last = last.next;

    last.next = entry;
  }
Example #2
0
 public void remove(Node node) {
   Node remove = node;
   remove.data = node.next.data;
   remove.next = node.next.next;
 }
Example #3
0
  public static void hasLoop(Node first) {
    // If list is empty no loop exists
    if (first == null) {
      System.out.println("List empty!");
    }

    // Set tortoise to the start of the list
    Node tortoise = new Node(first.getElement(), first.getNext());
    // Set hare to next element
    Node hare = new Node(tortoise.getNext().getElement(), tortoise.getNext());

    while (tortoise != hare) {
      // Move tortoise one position
      tortoise = tortoise.getNext();

      // Move hare two positions
      if (hare == null) {
        System.out.println("No cycle found"); // reached the end, no cycle
        break;
      } else {
        hare = hare.getNext().getNext();
      }

      // Cycle found
      if (tortoise == hare) {
        // Reset tortoise to start of list
        tortoise = new Node(first.getElement(), first.getNext());
        int mu = 0;

        // Move tortoise and hare at one step each
        // Tortoise and hare will intersect again at start of cycle
        while (tortoise != hare) {
          tortoise = tortoise.getNext();
          hare = hare.getNext();
          mu += 1;
        }

        hare = tortoise.getNext();
        int lam = 1;

        // Hare moves one step at a time until it meets tortoise
        // to determine the lenght of the cycle
        while (tortoise != hare) {
          hare = hare.getNext();
          lam += 1;
        }

        // Feedback
        System.out.println("Cycle found!");
        System.out.println("Cycle starts at: " + mu);
        System.out.println("Cycle length: " + lam);
      }
    }
  }