**
6-13 删除单链表偶数节点 (20 分)
**原创文章,欢迎转载,转载时请附上链接: https://blog.csdn.net/weixin_43527871/article/details/89524900 **
相似题型: 6-11 单链表结点删除 (20 分) https://blog.csdn.net/weixin_43527871/article/details/89523815
相似题型:6-12 学生成绩链表处理 (20 分) https://blog.csdn.net/weixin_43527871/article/details/89524183
**
本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中偶数值的结点删除。链表结点定义如下:
struct ListNode {
int data;
struct ListNode *next;
};
函数接口定义:
struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );
函数createlist从标准输入读入一系列正整数,按照读入顺序建立单链表。当读到−1时表示输入结束,函数应返回指向单链表头结点的指针。
函数deleteeven将单链表head中偶数值的结点删除,返回结果链表的头指针。
**
裁判测试程序样例:
**
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );
void printlist( struct ListNode *head )
{
struct ListNode *p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
struct ListNode *head;
head = createlist();
head = deleteeven(head);
printlist(head);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
1 2 2 3 4 5 6 7 -1
输出样例:
1 3 5 7
我的代码如下:
struct ListNode *createlist()
{
struct ListNode *head,*p;
head=(struct ListNode *)malloc(sizeof(struct ListNode ));
p=head;head->next =NULL;
int num;
while(scanf("%d",&num)!=EOF&&num!=-1)
{
p->next =(struct ListNode *)malloc(sizeof(struct ListNode ));
p=p->next ;
p->data =num;
p->next =NULL;
}
head=head->next ;
return (head);
}
struct ListNode *deleteeven( struct ListNode *head )
{
struct ListNode *p,*q;
if( head==NULL)
{
return NULL;
}
p=head;q=p->next ;
while(q!=NULL)
{
if(q->data %2==0)
{
p->next =q->next ;
free(q);
q=p->next ;
}
else
{
p=p->next ;
q=p->next ;
}
}
if( head->data %2==0)
{
head=head->next ;
}
return (head);
}
链表操作经验:
/*链表固定套路一:函数从标准输入读入一系列正整数,按照读入顺序建立单链表。
当读到#某个值#(通常是0或-1)时表示输入结束,函数应返回指向单链表头结点的指针。*/
/*
struct ListNode *readlist()
{
int num;
struct ListNode *head,*p;
head=(struct ListNode*)malloc(sizeof(struct ListNode));
p=head;
while(scanf("%d",&num )!=NULL&&num!=-1)
{
p->next =(struct ListNode*)malloc(sizeof(struct ListNode));
p=p->next ;
p->data =num;
p->next=NULL;
}
head=head->next ;
return (head);
}
*/
/*链表固定套路二:函数将单链表L中所有#符合某一条件#(例如:大于、等于、小于某个值
或 是奇数、偶数)的结点删除。返回指向结果链表头结点的指针。*/
/*
struct ListNode *deletem( struct ListNode *L, int m )
{
struct ListNode *p,*q;
if(L==NULL)
{
return NULL;
}
p=L;q=p->next ;
while(q)
{
if( q->data ==m )
{
p->next =q->next ;
free(q);
q=p->next ;
}
else
{
p=p->next ;
q=p->next ;
}
}
if(L->data ==m )
{
L=L->next ;
}
return L;
}
*/
更多内容,请关注我的博客