Is my approach is correct?
Hey @prathamesh.kalebere
Q [Is my approach is correct?
Answer Nope
5
2 4 1 3 5
correct output : 1 3 5 2 4
your code Gives : 5 3 1 2 4
Is that means both odd and even linked list should be sorted?
This works well but approach is correct??
public void evenAfterOdd() throws Exception{
Node temp = this.head;
int c = 0;
for (int i = 0; i < this.size; i++) {
if(temp.data % 2 != 0){
this.addAt(c++, this.removeAt(i));
}
temp = temp.next;
}
}
Then explain the approach, please?
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.
Okk, I got it. Thanks!