Skip to content

Commit 5033bd5

Browse files
committed
Added FindMiddleNode, FindMiddleNodeTest, ListNode, and corresponding JUnit test
1 parent 3eb521b commit 5033bd5

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
public class FindMiddleNode {
4+
5+
public static ListNode findMiddle(ListNode head) {
6+
ListNode slow = head;
7+
ListNode fast = head;
8+
while (fast != null && fast.next != null) {
9+
slow = slow.next;
10+
fast = fast.next.next;
11+
}
12+
return slow;
13+
}
14+
15+
public static void main(String[] args) {
16+
// Example: create a linked list 1->2->3->4->5
17+
ListNode head = new ListNode(1);
18+
head.next = new ListNode(2);
19+
head.next.next = new ListNode(3);
20+
head.next.next.next = new ListNode(4);
21+
head.next.next.next.next = new ListNode(5);
22+
23+
ListNode middle = findMiddle(head);
24+
System.out.println("Middle node value: " + middle.value);
25+
}
26+
}
27+
// package com.thealgorithms.datastructures.lists;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
public class ListNode {
4+
int value;
5+
ListNode next;
6+
7+
public ListNode(int value) {
8+
this.value = value;
9+
this.next = null;
10+
}
11+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
6+
public class FindMiddleNodeTest {
7+
8+
@Test
9+
public void testOddLengthList() {
10+
ListNode head = createList(new int[]{1, 2, 3, 4, 5});
11+
assertEquals(3, FindMiddleNode.findMiddle(head).value);
12+
}
13+
14+
@Test
15+
public void testEvenLengthList() {
16+
ListNode head = createList(new int[]{1, 2, 3, 4, 5, 6});
17+
assertEquals(4, FindMiddleNode.findMiddle(head).value);
18+
}
19+
20+
private ListNode createList(int[] values) {
21+
ListNode head = new ListNode(values[0]);
22+
ListNode current = head;
23+
for (int i = 1; i < values.length; i++) {
24+
current.next = new ListNode(values[i]);
25+
current = current.next;
26+
}
27+
return head;
28+
}
29+
}
30+

0 commit comments

Comments
 (0)