What is the error in my logic?
int n = size;
Node curr = head;
for(int i = 0; i<n; i++){
if(curr.data%2==0){
addLast(removeAt(i));
}
curr = curr.next;
}
Even After Odd Problem
Test case:
6
1 4 3 8 5 6
Correct answer:
1 3 5 4 8 6
Your answer:
1 3 8 6 5 4
You need to put all the odd elements in the order they are in the test case and after that the even elements in the order they are given in the testcase.
Intuition :
We can take two pointers before and after to keep track of the two linked lists as described above. These two pointers could be used two create two separate lists and then these lists could be combined to form the desired reformed list.
Algo :
- Take Two Fake_heads to take care of odd and even list.
- Put loop on the given LinkedList.
- If the node is odd add it to odd fake_ head list.
- If the node is Even add it to the even fake_head list.
- At the set connect both of the list together and set head to odd list.