Given a linked list, the task is to rearrange the linked list in the following manner:
- Reverse the second half of given linked list.
Rearrange the linked list such that:
- 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.
Similarly, arrange all elements in the alternate manner i.e. take 3rd element of the linked list from first half and 4th element of the linked list from 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
Approach: 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.
- Merge a linked list into another linked list at alternate positions
- Iterative Merge Sort for Linked List
- Merge two sorted linked list without duplicates
- Merge Sort for Doubly Linked List
- In-place Merge two linked lists without changing links of first list
- Merge two sorted linked lists such that merged list is in reverse order
- Merge K sorted Doubly Linked List in Sorted Order
- Create new linked list from two given linked list with greater element at each node
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Merge two sorted linked lists
- Merge Sort for Linked Lists
- Merge K sorted linked lists | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : 29AjayKumar