Test Case 0 is failing others are passing.
public void evenAfterOdd() throws Exception {
int lCount=0;
for(int i=0;i<this.size;i++) {
int val=getAt(i);
if(val%2==0) {
removeAt(i);
addLast(val);
}else {
removeAt(i);
addAt(lCount,val);
lCount++;
}
}
}
1 test case is failing
I can’t seem to understand how this is happening. Even 6 is being shifted before 8 which should not be happening as I am adding all the even numbers in the end and even the issue with 4. Is this due to lCount variable? If i remove it then Test case 1 also fails, i.e when I just remove the even nodes and shift them to the end without touching the Odd nodes.
@Rishabh8488,
When you remove an element at ith positon and add it at last, you skip an element.
https://ide.codingblocks.com/s/254552 corrected code using the approach you took.
Some errors:
- Count the number of even numbers, in order to add a condition to break the loop.
- See, if you use curr.data%2==0, the element at curr and removeAt(i) will be different. So, just get the element at index i and check if its even. And keep a count on number of even elements you have added at the back. And do
count--andi--when you move an element to the back of the linked list.
You can try keeping a previous node variable to optimize it futher.
Also something to look out for, the time complexity of your code is quite large as compared to the approach I mentioned below.
https://ide.codingblocks.com/s/254543 corrected code using the approach I have mentioned below.
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.
Oh ok. Thanks for the help!