Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.thealgorithms.datastructures.lists;

public final class FindMiddleNode {

private FindMiddleNode() {
throw new UnsupportedOperationException("Utility class");
}

public static ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}

public static void main(String[] args) {
// Example: create a linked list 1->2->3->4->5
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);

ListNode middle = findMiddle(head);
System.out.println("Middle node value: " + middle.value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.thealgorithms.datastructures.lists;

public class ListNode {
int value;
ListNode next;

public ListNode(int value) {
this.value = value;
this.next = null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.thealgorithms.datastructures.lists;

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

public class FindMiddleNodeTest {

@Test
public void testOddLengthList() {
ListNode head = createList(new int[] { 1, 2, 3, 4, 5 });
assertEquals(3, FindMiddleNode.findMiddle(head).value);
}

@Test
public void testEvenLengthList() {
ListNode head = createList(new int[] { 1, 2, 3, 4, 5, 6 });
assertEquals(4, FindMiddleNode.findMiddle(head).value);
}

private ListNode createList(int[] values) {
ListNode head = new ListNode(values[0]);
ListNode current = head;
for (int i = 1; i < values.length; i++) {
current.next = new ListNode(values[i]);
current = current.next;
}
return head;
}
}
Loading