Commit 6f5a7b87 authored by Fokion Zervoudakis's avatar Fokion Zervoudakis

Implement Floyd's cycle-detection algorithm.

parent 89971454
......@@ -19,8 +19,7 @@ class SLList<T> {
class Stack {
void push(T t) {
Node<T> n = new Node<>();
n.t = t;
Node<T> n = new Node<>(t);
n.next = head;
head = n;
if (len == 0) {
......@@ -49,8 +48,7 @@ class SLList<T> {
class Queue {
void add(T t) {
Node<T> n = new Node<>();
n.t = t;
Node<T> n = new Node<>(t);
if (len == 0) {
head = n;
} else {
......@@ -78,10 +76,34 @@ class SLList<T> {
}
}
static Node floyd(Node N) {
Node T, H;
try {
T = N.next;
H = N.next.next;
while (T != H) {
T = T.next;
H = H.next.next;
}
} catch (Exception e) {
return null;
}
T = N;
while (T != H) {
T = T.next;
H = H.next;
}
return T;
}
static class Node<T> {
T t;
Node<T> next;
Node(T t) {
this.t = t;
}
@Override
public String toString() {
return "[" + t + "] -> " + next;
......
package datastructure;
import datastructure.SLList.Node;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class SLList_floyd {
@Test
void itReturnsNullWhenTheListIsNull() {
assertNull(SLList.floyd(null));
}
@Nested
class WhenTheListIsNotNull {
private Node<Integer> N1;
@BeforeEach
void beforeEach() {
N1 = new Node<>(1);
}
@Test
void itReturnsNullWhenTheListHasOneNode() {
assertNull(SLList.floyd(N1));
}
@Test
void itReturnsNullWhenTheListHasManyNodesWithoutACycle() {
var N2 = new Node<>(2);
var N3 = new Node<>(3);
var N4 = new Node<>(4);
N1.next = N2;
N2.next = N3;
N3.next = N4;
assertNull(SLList.floyd(N1));
}
@Test
void itReturnsTheStartOfTheCycleWhenTheListHasOneNode() {
N1.next = N1;
assertEquals(N1, SLList.floyd(N1));
}
@Test
void itReturnsTheStartOfTheCycleWhenTheListHasTwoNodes() {
var N2 = new Node<>(2);
N1.next = N2;
N2.next = N1;
assertEquals(N1, SLList.floyd(N1));
}
@Test
void itReturnsTheStartOfTheCycleWhenTheListHasManyNodes() {
var N2 = new Node<>(2);
var N3 = new Node<>(3);
var N4 = new Node<>(4);
N1.next = N2;
N2.next = N3;
N3.next = N4;
N4.next = N2;
assertEquals(N2, SLList.floyd(N1));
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment