PTA删除单链表偶数节点(C语言)

读题:

本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中偶数值的结点删除。链表结点定义如下:

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;
}

作答代码:

typedef struct ListNode az;
int cnt=0,cot=0,cmt=0;
struct ListNode *createlist(){
  az *head1=(az *)malloc(sizeof(az)),*tail1=head1;
    head1->next=NULL;
    int t;
    while(1){
        scanf("%d",&t);
        if(-1==t) break;
        az *p=(az *)malloc(sizeof(az));
        p->data=t;
        if(t%2){cmt++;}else{cot++;}
        cnt++;
        p->next=NULL;
        tail1->next=p;
        tail1=tail1->next;
    }
   return head1;
}
struct ListNode *deleteeven( struct ListNode *head ){
    if(cmt==cnt) return head->next;
    if(cot==cnt) return NULL;
    az *o=head,*p=o->next,*pp=p->next;
    int x=0;
    for(int i=0;i<cnt-1;i++){
        if(p->data%2==0){
            x=1;
            free(p);
            o->next=pp;
        }
        p=pp;
        if(pp->next) pp=pp->next;
        if(x==1) x=0;
        else o=o->next;
    }
    if(p->data%2==0){free(p);o->next=NULL;}
    return head->next;
}

输入样例:

1 2 2 3 4 5 6 7 -1

输出样例:

1 3 5 7 

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

相关推荐

  1. PTA删除偶数节点C语言

    2023-12-26 20:08:01       39 阅读
  2. 删除的重复节点

    2023-12-26 20:08:01       12 阅读
  3. PTA-6-16 删除的重复结点

    2023-12-26 20:08:01       21 阅读
  4. C++ 删除中重复的节点 *

    2023-12-26 20:08:01       36 阅读
  5. C语言实现

    2023-12-26 20:08:01       41 阅读
  6. C语言数据结构——

    2023-12-26 20:08:01       44 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-26 20:08:01       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-26 20:08:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-26 20:08:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-26 20:08:01       18 阅读

热门阅读

  1. GBASE南大通用-管理用户定义函数(UDF)

    2023-12-26 20:08:01       38 阅读
  2. 【力扣100】199.二叉树的右视图

    2023-12-26 20:08:01       40 阅读
  3. C++精进之路(4)复合类型

    2023-12-26 20:08:01       36 阅读
  4. AI论文范文:AIGC中的图像转视频技术研究

    2023-12-26 20:08:01       31 阅读
  5. apt-get install和apt install有什么区别

    2023-12-26 20:08:01       45 阅读
  6. PTA 数组元素循环右移问题(C语言)

    2023-12-26 20:08:01       183 阅读
  7. CF1869 D2. Candy Party (Easy&Hard Version) [二进制贪心]

    2023-12-26 20:08:01       34 阅读