What’s wrong with my code?
Run time error on all test cases
Algorithm:
…1) Get pointer to the last node.
…2) Move all the even nodes to the end.
………a) Consider all even nodes before the first odd node and move them to end.
………b) Change the head pointer to point to the first odd node.
………b) Consider all even nodes after the first odd node and move them to the end.
Method 2
The idea is to split the linked list into two: one containing all even nodes and other containing all odd nodes. And finally attach the odd node linked list after the even node linked list.
To split the Linked List, traverse the original Linked List and move all odd nodes to a separate Linked List of all odd nodes. At the end of loop, the original list will have all the even nodes and the odd node list will have all the odd nodes. To keep the ordering of all nodes same, we must insert all the odd nodes at the end of the odd node list. And to do that in constant time, we must keep track of last pointer in the odd node list.
take four pointers and initialise all to NULL
oddend and evenend to store the ends of even number and odd numbers
and oddstart and evenstart to store the beginning of them
check the first node if it is odd or even and point oddstart or evenstart accordingly
now for temp = head->next start running a loop
in the loop:
if an odd number is encountered and if oddstart is NULL point oddstart to it else if oddstart->next==NULL point odd end else point oddend->next to this temp and move oddend to it next
similarly follow the simlar steps for even numbers
at the end of the loop point oddend to even start and return oddstart as your new head
please check the code.
This is the reply to your other doubt, they have the same mistake, in creating the linked list, check the creation once please and also mind the input format
You send the wrong code. Please check once.
Check this. it says TLE.