PTA:链表 删除单链表偶数节点

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

struct ListNode {
    int data;
    struct ListNode *next;
};

函数接口定义:

struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );

函数createlist从标准输入读入一系列正整数,按照读入顺序建立单链表。当读到−1时表示输入结束,函数应返回指向单链表头结点的指针。

函数deleteeven将单链表head中偶数值的结点删除,返回结果链表的头指针。

裁判测试程序样例:

#include 
#include 

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=NULL;
    struct ListNode *tail=NULL;
    int num;
    while(1)
    {
        scanf("%d",&num);
        if(num==-1)
        {
            break;
        }
        struct ListNode *newnode=(struct ListNode *)malloc(sizeof(struct ListNode));
        newnode->data=num;
        newnode->next=NULL;
        if(head==NULL)
        {
            head=newnode;
            tail=newnode;
        }else{
            tail->next=newnode;//在链表结构上把新节点连接到当前链表的尾部,实现链表的扩展
            tail=newnode;//更新尾指针,使其指向新的尾节点,保证后续插入操作能够正确地在链表尾部进行
        }
    }
    return head;
}
struct ListNode *deleteeven( struct ListNode *head )
{
    struct ListNode *current=head;
    struct ListNode *prev=NULL;
    while(current!=NULL&¤t->data%2==0)//头节点为偶数
    {
        struct ListNode *temp=current;
        current=current->next;//将current指针移动到下一个节点
        free(temp);
        head=current;
    }
    while(current!=NULL)
    {
        while(current!=NULL&¤t->data%2==0)
        {
            struct ListNode *temp=current;
            current=current->next;//将current指针移动到下一个节点
            prev->next=current;//更新prev节点的next指针,使其跳过当前的偶数节点
            free(temp);
        }
        if(current!=NULL)
        {
            prev=current;
            current=current->next;
        }
    }
    return head;
}

 

你可能感兴趣的:(C语言PTA习题,链表,数据结构)