Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
Put the odd nodes in a linked list and the even nodes in another. Then link the evenList to the tail of the oddList.\n
The solution is very intuitive. But it is not trivial to write a concise and bug-free code.\n
LinkedList need two pointers head and tail to support operations at both ends. The variables
odd are the head pointer and tail pointer of one
LinkedList we call oddList; the variables
even are the head pointer and tail pointer of another
LinkedList we call evenList. The algorithm traverses the original LinkedList and put the odd nodes into the oddList and the even nodes into the evenList. To traverse a LinkedList we need at least one pointer as an iterator for the current node. But here the pointers
even not only serve as the tail pointers but also act as the iterators of the original list.
The best way of solving any linked list problem is to visualize it either in your mind or on a piece of paper. An illustration of our algorithm is following:\n
Figure 1. Step by step example of the odd and even linked list.\n\n
Time complexity : . There are total nodes and we visit each node once.\n
Space complexity : . All we need is the four pointers.\n