I think I have done everything correct, but still it’s giving wrong answer for last test case. why?
Here I am first checking if an even number occurs, if an even number occurs, I store it’s address and as any odd number occurs afterwards, I swap both the number.
my code is
#include
using namespace std;
struct Node{
int data;
Node* next;
};
Node* createnode(int data){
Node* temp=new(Node);
temp->data=data;
temp->next=NULL;
return temp;
}
Node* insertend(Node* head,int data){
Node* nod=createnode(data);
if(head==NULL){
return nod;
}
Node* temp=head;
while(head->next!=NULL){
head=head->next;
}
head->next=nod;
return temp;
}
void print(Node* head){
while(head!=NULL){
printf("%d “,head->data);
head=head->next;
}
printf(”\n");
}
void odbeven(Node* head){
Node* temp=NULL;
int x;
while(head!=NULL){
x=head->data;
if(x%2==1){
if(temp!=NULL){
x=temp->data;
temp->data=head->data;
head->data=x;
temp=temp->next;
}
}
else{
if(temp==NULL)
temp=head;
}
head=head->next;
}
}
int main() {
int n;
scanf("%d",&n);
Node* head=NULL;
int x;
for(int i=0;i<n;i++){
scanf("%d",&x);
head=insertend(head,x);
}
odbeven(head);
print(head);
return 0;
}
Even-after-odd problem in linked list
Hi @pulkit_99
Your code is failing test case that is 1 2 4 3 8 5 6. In this your code is printing output as 1 3 5 2 8 4 6 but in correct output 8 should come after 4 as in the input it is after 4 only. Try to think and handle these test cases.
By the way simple approach for this question should be :
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.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.