Given a linked list, reverse alternate nodes and append them to the end of the list. Extra allowed space is O(1)
Input: 1->2->3->4->5->6 Output: 1->3->5->6->4->2 Explanation: Two lists are 1->3->5 and 2->4->6, reverse the 2nd list: 6->4->2. Merge the lists Input: 12->14->16->18->20 Output: 12->16->20->18->14 Explanation: Two lists are 12->16->20 and 14->18, reverse the 2nd list: 18->14. Merge the lists
- The idea is to maintain two linked lists, one list of all odd positioned nodes and other list of all even positioned nodes .
- Traverse the given linked list which is considered as an odd list or oddly positioned nodes.
- If the node is even node, remove it from the odd list and add it to the front of even node list. Nodes are added at front to keep the reverse order.
- Append the even node list at the end of odd node list.
Linked list before calling rearrange() 1 2 3 4 5 6 7 Linked list after calling rearrange() 1 3 5 7 6 4 2
Time Complexity: O(n).
The above code simply traverses the given linked list. So time complexity is O(n)
Auxiliary Space: O(1).
No extra space is required.
This article is contributed by Aman Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Reverse alternate K nodes in a Singly Linked List
- Reverse alternate K nodes in a Singly Linked List - Iterative Solution
- Append the last M nodes to the beginning of the given linked list
- Merge a linked list into another linked list at alternate positions
- Alternate Odd and Even Nodes in a Singly Linked List
- Delete alternate nodes of a Linked List
- Print alternate nodes of a linked list using recursion
- Print the alternate nodes of linked list (Iterative Method)
- Product of the alternate nodes of linked list
- Sum of the alternate nodes of linked list
- Subtraction of the alternate nodes of Linked List
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- Double elements and append zeros in linked list
- Reverse nodes of a linked list without affecting the special characters
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- Rearrange a linked list in to alternate first and last element
- Delete N nodes after M nodes of a linked list
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes