69,373
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
struct stud_node{
int num;
struct stud_node *next;
};
void Ptrint_Stu_Doc(struct stud_node *head);
struct stud_node *create_nodes(void)
{
struct stud_node *head, *tail, *pnew;
int num, size=sizeof(struct stud_node);
scanf("%d",&num);
head = NULL;
while (num != -1) {
pnew = (struct stud_node *)malloc(size);
if (!pnew)
exit(0);
pnew->num = num;
if (!head) {
head = pnew;
tail = head;
} else {
tail->next = pnew;
tail = pnew;
}
scanf("%d",&num);
}
tail->next = NULL;
return head;
}
struct stud_node *get_odd_nodes(struct stud_node **head)
{
struct stud_node *odd_head, *odd_tail, *pcur, *prev;
odd_head = odd_tail = NULL;
prev = *head;
while (prev && prev->num % 2) {
if (prev->num % 2) {
pcur = prev;
if (!odd_head) {
odd_head = prev;
odd_tail = odd_head;
} else {
odd_tail->next = prev;
odd_tail = prev;
}
*head = prev->next;
}
prev = prev->next;
}
pcur = NULL;
if (prev)
pcur = prev->next;
while (pcur) {
if (pcur->num % 2) {
if (!odd_head) {
odd_head = pcur;
odd_tail = pcur;
} else {
odd_tail->next = pcur;
odd_tail = pcur;
}
prev->next = pcur->next;
pcur = pcur->next;
} else {
prev = prev->next;
pcur = pcur->next;
}
}
if (odd_tail)
odd_tail->next = NULL;
return odd_head;
}
int main(void)
{
struct stud_node *head, *odd_head;
head = create_nodes();
Ptrint_Stu_Doc(head);
odd_head = get_odd_nodes(&head);
printf("Odd nodes list: ");
Ptrint_Stu_Doc(odd_head);
Ptrint_Stu_Doc(head);
#if 0
structstud_node*L,*tail1,*tail2,*p1,*p2,*NEW,*ptr1,*ptr2;
int num;
int size=sizeof(struct stud_node);
L = tail1 = NULL;
scanf("%d",&num);
while(num != -1){
p1=(struct stud_node*)malloc(size);
p1->num = num;
p1->next = NULL;
if(L == NULL) {
L = p1;
tail1 = L;
} else {
tail1->next=p1;
}
tail1 = p1;
scanf("%d", &num);
}
/*---------*/
while(L && L->num % 2 == 0){
ptr1=L;
L = L->next;
free(ptr1);
}
if(L==NULL){
return;
}
ptr1=L;
ptr2=L->next;
while(ptr2!=NULL){
if(ptr2->num%2==0){
ptr1->next=ptr2->next;
}
else ptr1=ptr2;
ptr2=ptr2->next;
}
p1=L;
while(p1!=NULL) {
tail2=p2=NEW=NULL;
p2=(struct stud_node *)malloc(size);
p2->num=p1->num;
p2->next=NULL;
if(NEW==NULL) NEW=p2;
else tail2->next=p2;
tail2=p2;
p1=p1->next;
}
tail2->next=NULL;
#endif
//Ptrint_Stu_Doc(NEW);
}
void Ptrint_Stu_Doc(struct stud_node *head)
{
struct stud_node *ptr;
if(head==NULL){
printf("No Records\n");
return;
}
for(ptr=head;ptr;ptr=ptr->next)
printf("%d ",ptr->num);
printf("\n");
}
参考一下吧