Given a linked list and positions m and n. We need to reverse the linked list from position m to n.
Examples:
Input : linkedlist : 10->20->30->40->50->60->70->NULL , m = 3 and n = 6 Output : 10->20->60->50->40->30->70->NULL Explanation: Linkedlist reversed starting from the node mi.e. 30 and n i.e. 60
Input : linkedlist : 1->2->3->4->5->6->NULL , m = 2 and n = 4 Output : 1->4->3->2->5->6->NULL Explanation: Linkedlist reversed starting from the node mi.e. 2 and n i.e. 4
[Expected Approach - 1] Using Two Traversal - O(n) time and O(1) Space:
The idea is to reverse a segment of the linked list by locating the start and end nodes, removing the links and reversing the segment using standard reverse function, and then reattaching it back to the main list.
Step-by-step approach :
Find the start and end positions of the linked list by running a loop.
Unlink the portion of the list that needs to be reversed from the rest of the list.
Reverse the unlinked portion using the standard linked list reverse function.
Time Complexity: O(n), Here n is the number of nodes in the linked list. In the worst case we need to traverse the list twice. Auxiliary Space: O(1).
[Expected Approach - 2] Using Single Traversal - O(n) time and O(1) Space:
The idea is to get pointers to the head and tail of the reversed segment, the node before the mth node, and the node after the nth node and then reverse the segment and reconnect the links appropriately.
Follow the steps below to solve the problem:
Get the pointer to the head and tail of the reversed linked list.
Get the pointer to the node before mth and node after nth node.
Reverse the list using standard linked list reverse function.