Reverse a Linked List in Groups of Given Size
Create a function that would reverse every t nodes in a linked list (where t is an input to the function).
Example:
Algorithm: reverse(head, t)
- Reverse the first t-th sub-list. Maintain track of the next and previous nodes when reversing. Let next be the pointer to the next node and prev be the pointer to the previous node.
- Head -> next = reverse (next, t) (Recursively obtain the rest of the list and connect the two sub-lists)
- Return prev(prev becomes the new list's head).
The illustration below displays how the reverse process is functioning:
The given technique is implemented as follows:
C Program:
Output:
Given linked list
11 12 13 14 15 16 17 18 19
Reversed Linked list
13 12 11 16 15 14 19 18 17
Analysis of Complexity:
- Time Complexity will be O (n).
The list is traversed just once, and it contains 'n' elements.
- Auxiliary Space will be O(n/t).
During the recursion, calls will be performed for each Linked List of size n, n/t, or (n/t)+1.
This problem can be solved in O(1) Space Complexity.
Approach - 2 (Space Optimization - Iterative)
This Algorithm necessitates the following steps:
- Make a duplicate node and point it to the input's head, as in duplicate -> next = head.
- Determine the size of the linked list in O(N) time, where N is the linked list's size.
- For each group, initialise three-pointers prior, curr, and next to reverse t elements.
- Iterate through the linked lists until next!=NULL is reached.
- curr points to the previous->next and next to the curr next.
- Then, using the inner for loop, reverse the specific group using the following four steps:
- curr->next = next->next
- next->next = prev->next
- prev->next = next
- next = curr->next
- For all groups except the final remaining member, this for loop runs for t-1 times; for the last remaining element, it runs for the length of the linked list minus one.
- To estimate the size of the remaining linked list, increment count after the for loop by t cnt -= t.
- Set the prev position to curr, so that prev = curr.
The code for the aforementioned algorithm is provided below.
C Program:
C++ Program:
Output:
Given linked list
11 12 13 14 15 16 17 18 19
Reversed Linked list
13 12 11 16 15 14 19 18 17
Analysis of Complexity:
- Time Complexity will be O(N).
The while loop consumes O(N/t) time, whereas the inner for loop consumes O(t) time.
- Auxiliary Space will be O(1).
There is no extra space used.
|