链表删除奇数值结点

来源:百度知道 编辑:UC知道 时间:2024/06/07 12:53:22
#include <stdio.h>
#include <stdlib.h>
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode LNode;
LNode * LinkList_Create(int n)
{
LNode *p,*head,*tail;
int i;
head=(LNode *)malloc(sizeof(LNode));
head->data=0;
tail=head;
for(i=1;i<=n-1;i++)
{
p=(LNode *)malloc(sizeof(LNode));
p->data=i;
tail->next=p;
tail=p;
}
tail->next=NULL;
return(head);
}
void LinkList_delete(LNode *head)
{
LNode *p,*q;
p=head->next;
while(p->next!=NULL)
{
if(head->data%2!=0)
{
q=head;
head=head->next;
p=head->next;
free(q);
}
else
{
if(p->data%2!=0)
{
head->next=p->next;
q=p;
p=p->next;

你的LinkList_delete函数写法有问题,造成了死循环,而且解决完死循环之后最终只能剩下的是最头和尾的两个偶数值的节点了。所以我直接将LinkList_delete函数改写了。
#include <stdio.h>
#include <stdlib.h>
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode LNode;

LNode * LinkList_Create(int n)
{
LNode *p,*head,*tail;
int i;
head=(LNode *)malloc(sizeof(LNode));
head->data=0;
tail=head;
for(i=1;i<=n-1;i++)
{
p=(LNode *)malloc(sizeof(LNode));
p->data=i;
tail->next=p;
tail=p;
}
tail->next=NULL;
return(head);
}
void LinkList_delete(LNode *head)
{
LNode *p,*q,*tmp;
p=head;
q=NULL;

while(p!=NULL)
{
if(p->data%2==0)
{
q=p;
p=p->next;
}
else
{
q->next=p->next;
tmp=p;
p=p->next;
free(tmp);

}
}
}

void ma