- #1
evinda
Gold Member
MHB
- 3,836
- 0
Hello! (Wave)
Consider a singly-linked list [m] L[/m] each element of which is a struct with two fields, an integer [m]num[/m] and a pointer [m]next[/m] to the next element of the list.
Describe an algorithm that gets as argument a pointer to the first element of the list [m]L[/m] and that creates a new list [m]L'[/m] that will contain all the elements of [m]L[/m] ordered in the following way:
The elements of [m]L[/m] for which the field [m]num[/m] is an odd number have to appear in [m]L'[/m] before all the elements of which the field [m]num[/m] is an even number. The elements with an odd number at the field [m]num[/m] should keep in [m]L'[/m] the display order that they had at the initial list [m]L[/m].
The same should hold for the elements with an even number at the field [m]num[/m].
For example, if the initial list is [m]L=13->15->20->17->24->26->9->30->53->44[/m] the final list should be [m]L'=13->15->17->9->53->20->24->26->50->44[/m].That's what I have tried:
Could you tell me if it is right?
Consider a singly-linked list [m] L[/m] each element of which is a struct with two fields, an integer [m]num[/m] and a pointer [m]next[/m] to the next element of the list.
Describe an algorithm that gets as argument a pointer to the first element of the list [m]L[/m] and that creates a new list [m]L'[/m] that will contain all the elements of [m]L[/m] ordered in the following way:
The elements of [m]L[/m] for which the field [m]num[/m] is an odd number have to appear in [m]L'[/m] before all the elements of which the field [m]num[/m] is an even number. The elements with an odd number at the field [m]num[/m] should keep in [m]L'[/m] the display order that they had at the initial list [m]L[/m].
The same should hold for the elements with an even number at the field [m]num[/m].
For example, if the initial list is [m]L=13->15->20->17->24->26->9->30->53->44[/m] the final list should be [m]L'=13->15->17->9->53->20->24->26->50->44[/m].That's what I have tried:
Code:
List(L){
if (L==NULL) return;
node *p=NULL, *q=L, *l=L, *L3=NULL, *head2=NULL, *tail1=NULL, *tail2=NULL;
while (q!=NULL){
if (q-> num mod 2==1){
if (p==NULL){
p->num=q->num;
L3=p;
}
else {
p=p->next;
p->num=q->num;
}
}
}
tail=p;
while (l!=NULL){
if (l-> num mod 2==0){
if (l==NULL){
l->num=q->num;
head2=l;
}
else {
l=l->next;
l->num=q->num;
}
}
}
tail2=q;
tail1->next=head2;
tail1=tail2;
return L3;
}