本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中偶数值的结点删除。链表结点定义如下:
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 *pHead,*pnew,*pEnd;
pHead=NULL;
pnew=pEnd=(struct ListNode *)malloc(sizeof(struct ListNode));
if(pnew==NULL)return NULL;
scanf("%d",&pnew->data);
if(pnew->data!=-1){
pHead=pnew;
}
while(pnew->data!=-1){
pnew=(struct ListNode*)malloc(sizeof(struct ListNode));
scanf("%d",&pnew->data);
if(pnew->data!=-1){
pEnd->next=pnew;
pEnd=pnew;
}
}
free(pnew);
return pHead;
}
struct ListNode *deleteeven(struct ListNode *head){
struct ListNode *p,*ptemp;//要首先处理头指针是否符合条件
while(head!=NULL){
if(head->data%2==0){
p=head;
head=head->next;
free(p);
}else{
break;
}
}
if(head==NULL)return NULL;
p=head;
ptemp=p->next;
while(ptemp!=NULL){
if(ptemp->data%2==0){
p->next=ptemp->next;
free(ptemp);
}else{
p=ptemp;
}
ptemp=p->next;
}
return head;
}
这篇博客介绍了如何实现两个C语言函数,一个用于从标准输入创建单链表,另一个用于删除链表中所有偶数值的节点。示例代码展示了如何处理链表数据结构,包括链表节点的定义、链表的创建以及删除指定条件的节点。
6707

被折叠的 条评论
为什么被折叠?



