Merge first half and reversed second half of the linked list alternatively
Given a linked list, the task is to rearrange the linked list in the following manner:
- Reverse the second half of given linked list.
- First element of the linked list is the first element of first half.
- Second element of the linked list is the first element of second half.
Input: 1->2->3->4->5 Output: 1->5->2->4->3 Input: 1->2->3->4->5->6 Output: 1->6->2->5->3->4
Initially find the mid node of the linked list. The approach has been discussed here. Reverse the linked list from mid to end. Once the linked list is reversed, traverse from the start and insert a node from the first half of the list and another node from the back half of the linked list simultaneously. Continue this process until the middle node is reached.
Once the middle node is reached, point the node just before the middle node to NULL.
Below is the implementation of the above approach:
Before Modifying: 1->2->3->4->5 After Modifying: 1->5->2->4->3 Before Modifying: 1->2->3->4->5->6 After Modifying: 1->6->2->5->3->4
Time Complexity: O(N)
Exercise: Solve the question without reversing the Linked List from the middle node.
My Personal Notes arrow_drop_up
Please Login to comment...