删除单链表偶数节点代码里哪里有问题?

img


pta上提交后显示有三个段错误是哪里错啊?


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

/* 你的代码将被嵌在这里 */
struct ListNode *createlist(){
    struct ListNode *head,*q,*t;
    head = (struct ListNode*)malloc(sizeof(struct ListNode));
    q = head;
    int a;
    while(scanf("%d",&a),a != -1){
        t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->data = a;
        q->next = t;
        q = t;
    }
    q->next = NULL;
    return head->next;
}
struct ListNode *deleteeven( struct ListNode *head ){
    struct ListNode *q,*p;
    while(head->data % 2 == 0 && head) head = head->next;
    if(head == NULL) return NULL;
    q = head;
    p = q->next;
    while(p->next){
        p = q->next;
        if(p->data % 2 == 0){
            q->next = p->next;
        }
        else q = q->next;
    }
    return head;
}

题主的代码里,如果输入的全是偶数,执行struct ListNode *deleteeven()函数时出错。修改如下,供参考:

#include <stdlib.h>
#include <stdio.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;
}
/* 你的代码将被嵌在这里 */
struct ListNode *createlist()
{
    struct ListNode *head = NULL,*q = NULL,*t;
    int a;
    while(scanf("%d",&a),a != -1){
        t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->next = NULL;
        t->data = a;
        if (!head)
            head = t;
        else
            q->next = t;
        q = t;
    }
    return head;
}
struct ListNode *deleteeven( struct ListNode *head )
{
    struct ListNode *q,*p = NULL;
    q = head;
    while(q)
    {
        if(q->data % 2 == 0)
        {
            if (!p){
                head = head->next;
                free(q);
                q = head;
            }
            else{
                p->next = q->next;
                free(q);
                q = p->next;
            }
        }
        else{
            p = q;
            q = q->next;
        }
    }
    return head;
}