Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ The `next` variable points to the next node in the data structure and value stor
6. `MergeKSortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient sorting algorithm for linked list).
7. `RandomNode.java` : Selects a random node from given linked list and diplays it.
8. `SkipList.java` : Data Structure used for storing a sorted list of elements with help of a Linked list hierarchy that connects to subsequences of elements.
9. `TortoiseHareAlgo.java` : Finds the middle element of a linked list using the fast and slow pointer (Tortoise-Hare) algorithm.
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.thealgorithms.datastructures.lists;

public class TortoiseHareAlgo<E> {
static final class Node<E> {
Node<E> next;
E value;

private Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}

private Node<E> head = null;

public TortoiseHareAlgo() {
head = null;
}

public void append(E value) {
Node<E> newNode = new Node<>(value, null);
if (head == null) {
head = newNode;
return;
}
Node<E> current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}

public E getMiddle() {
if (head == null) {
return null;
}

Node<E> slow = head;
Node<E> fast = head;

while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}

return slow.value;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
Node<E> current = head;
while (current != null) {
sb.append(current.value);
if (current.next != null) {
sb.append(", ");
}
current = current.next;
}
sb.append("]");
return sb.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.thealgorithms.datastructures.lists;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

import org.junit.jupiter.api.Test;

class TortoiseHareAlgoTest {

@Test
void testAppendAndToString() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
list.append(10);
list.append(20);
list.append(30);
assertEquals("[10, 20, 30]", list.toString());
}

@Test
void testGetMiddleOdd() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
assertEquals(3, list.getMiddle());
}

@Test
void testGetMiddleEven() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
assertEquals(3, list.getMiddle()); // returns second middle
}

@Test
void testEmptyList() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
assertNull(list.getMiddle());
assertEquals("[]", list.toString());
}
}
Loading