Statement
Solution
Naive approach
The naive approach uses two pointers left
and right
to keep track of the sublist and reverse it. The pointers left
and right
are intialized to the head of the linked list.
We begin by moving the left
pointer to the node, that represents the start of the sublist and the right
pointer to the node, that represents the end of the sublist. Next, while the left
pointer is behind the right
pointer, we take the following steps:
-
We swap the values of the nodes pointed to by the
left
and theright
pointer. -
We move the
left
pointer one step forward to the node. -
Since we are given a singly linked list, and there is no
prev
, we can’t update theright
pointer in the same way as we did for theleft
pointer, i.e., moving it backward to the node. Instead, on each iteration, we reset theright
pointer to the head of the list and then move it forward to the node. -
We repeat steps 1–3 until both pointers meet at some point, or the
right
crossesleft
.
The time complexity of this solution is , since we’re swapping the nodes, and traversing the list per iteration. The space complexity of this solution , since we use a constant number of extra variables.