Skip to content

Commit 84d87ec

Browse files
Create TortoiseHareAlgorithm.java
Implement TortoiseHareAlgo with append, getMiddle, and toString methods - Added generic singly linked list with inner Node class - Implemented append() to add elements - Implemented getMiddle() using Tortoise-Hare approach - Added toString() for readable list representation
1 parent c691b31 commit 84d87ec

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
public class TortoiseHareAlgo<E> {
4+
static final class Node<E> {
5+
Node<E> next;
6+
E value;
7+
8+
private Node(E value, Node<E> next) {
9+
this.value = value;
10+
this.next = next;
11+
}
12+
}
13+
14+
private Node<E> head = null;
15+
16+
public TortoiseHareAlgo() {
17+
head = null;
18+
}
19+
20+
public void append(E value) {
21+
Node<E> newNode = new Node<>(value, null);
22+
if (head == null) {
23+
head = newNode;
24+
return;
25+
}
26+
Node<E> current = head;
27+
while (current.next != null) {
28+
current = current.next;
29+
}
30+
current.next = newNode;
31+
}
32+
33+
public E getMiddle() {
34+
if (head == null) return null;
35+
36+
Node<E> slow = head;
37+
Node<E> fast = head;
38+
39+
while (fast != null && fast.next != null) {
40+
slow = slow.next;
41+
fast = fast.next.next;
42+
}
43+
44+
return slow.value;
45+
}
46+
47+
@Override
48+
public String toString() {
49+
StringBuilder sb = new StringBuilder("[");
50+
Node<E> current = head;
51+
while (current != null) {
52+
sb.append(current.value);
53+
if (current.next != null) sb.append(", ");
54+
current = current.next;
55+
}
56+
sb.append("]");
57+
return sb.toString();
58+
}
59+
}

0 commit comments

Comments
 (0)