Singly Linked List Reversal — Variants and Edge Cases
You are given a standard singly linked list with nodes of the form:
-
Node fields: value, next
-
Head pointer may be null (empty list).
-
Assume 1-indexed positions for m and n.
Implement and analyze the following:
A) Reverse Entire List
-
Provide an iterative in-place solution that uses O(1) extra space.
-
Provide a recursive solution.
-
Analyze time and space complexity of both.
-
Explicitly handle edge cases: empty list, single-node list, and very long lists (stack depth considerations for recursion).
B) Reverse a Sublist [m, n]
-
Reverse the nodes from position m to n (inclusive), in-place, and return the head. Assume 1 ≤ m ≤ n ≤ length of list.
C) Reverse Nodes in k-Groups
-
Reverse the list in contiguous groups of size k using O(1) extra space. If the final group has fewer than k nodes, leave that tail group as-is.
D) Cycle Detection Before Reversal
-
Explain and implement how to detect a cycle in the list and reject (do not attempt to reverse) if a cycle is present.
You may use pseudo-code or code in a language of your choice.