Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers.
Extraction of Even and Appending Odds - O(n) Time O(1) Space
The Idea is to traverse the list and extract all even nodes while maintaining order. Build a separate even list and finally append the remaining odd nodes.
1. Create an empty result list 2. Traverse the input list and move all even value nodes from the original list to the result list. If our original list was 17->15->8->12->10->5->4->1->7->6. Then after this step, we get original list as 17->15->5->1->7 and result list as 8->12->10->4->6 3. Append the remaining original list to the end of res and return result
Output
8->2->4->6->17->15->9
Time Complexity: O(n) Auxiliary Space: O(1)
Maintaining Start and End - O(n) Time O(1) Space
The idea is to maintain two separate lists for even and odd nodes using dummy nodes. During traversal, append nodes to their respective lists and finally connect the even list to the odd list.
Initialize pointers for even and odd list , say evenStart , evenEnd and oddStart , oddEnd.
Separate nodes into even and odd lists during traversal.
Link the end of the even list to the start of the odd list.
Update the original list's head to the even list's head.