赞
踩
6-52 删除单链表偶数节点 (20 分)
本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中偶数值的结点删除。链表结点定义如下:
- 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() {
- int data;
- struct ListNode *head,*pre;
- head=pre=NULL;
- scanf("%d",&data);
- while(data!=-1) {
- struct ListNode *a=(struct ListNode *)malloc(sizeof(struct ListNode));
- a->data=data;
- a->next=NULL;
- if(head==NULL) {
- head=a;
- pre=a;
- } else {
- pre->next=a;
- pre=a;
- }
- scanf("%d",&data);
- if(data==-1)
- break;
- }
- return head;
- }
- struct ListNode *deleteeven( struct ListNode *head ) {
- struct ListNode *store,*i;//一个存上一个的地址,一个过度。
- int flag=0;
- for(i=head; i!=NULL;) {
- if((i->data)%2==0) {
- if(i==head) {
- store=i;
- head=head->next;
- i=head;
- free(store);
- continue;
- }
- if(i->next!=NULL) {
- store->next=i->next;
- i=store->next;
- flag=0;
- continue;
- } else if(i->next==NULL) {
- store->next=NULL;
- break;
- }
- } else {
- store=i;
- i=i->next;
- }
- }
- return head;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。