mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
Add Middle of Linked List (Slow/Fast Pointers) (#7212)
* feat: implement Smooth Sort algorithm with detailed JavaDoc and test class * style: format LEONARDO array for improved readability with clang-format * feat: add MiddleOfLinkedList class and corresponding test cases * docs: update documentation for MiddleOfLinkedList class * test: refactor MiddleOfLinkedListTest to improve readability and assertions * test: refactor MiddleOfLinkedListTest for improved null safety and readability --------- Co-authored-by: Ahmed Allam <60698204+AllamF5J@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package com.thealgorithms.datastructures.lists;
|
||||
|
||||
/**
|
||||
* Returns the middle node of a singly linked list using the two-pointer technique.
|
||||
*
|
||||
* <p>The {@code slow} pointer advances by one node per iteration while {@code fast} advances by two.
|
||||
* When {@code fast == null} or {@code fast.next == null}, {@code slow} points to the middle node.
|
||||
* For even-length lists, this returns the <em>second</em> middle node.</p>
|
||||
*
|
||||
* <p>This method does not modify the input list.</p>
|
||||
*
|
||||
* <p>Reference: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare</p>
|
||||
*
|
||||
* <p>Complexity:</p>
|
||||
* <ul>
|
||||
* <li>Time: {@code O(n)}</li>
|
||||
* <li>Space: {@code O(1)}</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class MiddleOfLinkedList {
|
||||
|
||||
private MiddleOfLinkedList() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the middle node of the list.
|
||||
*
|
||||
* @param head the head of the singly linked list; may be {@code null}
|
||||
* @return the middle node (second middle for even-sized lists), or {@code null} if {@code head} is {@code null}
|
||||
*/
|
||||
public static SinglyLinkedListNode middleNode(final SinglyLinkedListNode head) {
|
||||
if (head == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SinglyLinkedListNode slow = head;
|
||||
SinglyLinkedListNode fast = head;
|
||||
|
||||
while (fast != null && fast.next != null) {
|
||||
slow = slow.next;
|
||||
fast = fast.next.next;
|
||||
}
|
||||
|
||||
return slow;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user