Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes same as that of the original list, the task is just to rearrange the nodes such that all even valued nodes appear before the odd valued nodes.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> NULL
Output: 10 -> 8 -> 6 -> 4 -> 2 -> 1 -> 3 -> 5 -> 7 -> 9 -> NULL
Input: 4 -> 3 -> 2 -> 1 -> NULL
Output: 2 -> 4 -> 3 -> 1 -> NULL
The idea is to iteratively push all the elements of the linked list to deque as per the below conditions:
- Start traversing the linked list and if an element is even then push it to the front of the Deque and,
- If the element is odd then push it to the back of the Deque.
Finally, replace all elements of the linked list with the elements of Deque starting from the first element.
Below is the implementation of the above approach:
Given linked list: 1 2 3 4 5 6 7 8 9 10 After rearrangement: 10 8 6 4 2 1 3 5 7 9
Time complexity: O(N)
Auxiliary Space: O(N), where N is the total number of nodes in the linked list.
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.
- Segregate even and odd nodes in a Linked List
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Rearrange a linked list such that all even and odd positioned nodes are together
- Alternate Odd and Even Nodes in a Singly Linked List
- Find sum of even and odd nodes in a linked list
- Delete all odd or even positioned nodes from Circular Linked List
- deque::at() and deque::swap() in C++ STL
- deque::pop_front() and deque::pop_back() in C++ STL
- deque::front() and deque::back() in C++ STL
- deque::empty() and deque::size() in C++ STL
- deque::clear() and deque::erase() in C++ STL
- deque::operator= and deque::operator in C++ STL
- deque::begin() and deque::end in C++ STL
- deque::emplace_front() and deque::emplace_back() in C++ STL
- Implementation of Deque using doubly linked list
- Sum and Product of all even digit sum Nodes of a Singly Linked List
- Sum and Product of nodes with value as even digit sum in Circular Linked List
- Remove all even parity nodes from a Doubly and Circular Singly Linked List
- Check whether the length of given linked list is Even or Odd
- Sum of all odd frequency nodes of the Linked List
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 : andrew1234