#include <stdio.h>
#include <stdlib.h>

typedef struct lista_inteiros
{
    int valor;
    struct lista_inteiros *next;

}element_int;

void insere_inteiro(element_int **head, element_int **aux, int m);
void remove_inteiro(element_int **head, element_int **aux, int m);

int main()
{
    int i = 0;
    element_int *head, *aux;

    head = NULL;

    for(i = 0; i<6; i++)
    {
        insere_inteiro(&head, &aux, i);
    }

    aux = head;

    while(aux)
    {
        printf("%d\n", aux->valor);
        aux = aux->next;
    }

    aux = head;
    i = 4;

    remove_inteiro(&head, &aux, i);

    aux = head;
    while(aux)
    {
        printf("%d\n", aux->valor);
        aux = aux->next;
    }


    return 0;
}

void insere_inteiro(element_int **head, element_int **aux, int m)
{
    (*aux) = (element_int*)malloc(sizeof(element_int));
    if((*aux) == NULL)
    {
        printf("Error\n");
        exit(1);
    }

    (*aux)->valor = m;
    (*aux)->next = (*head);
    (*head) = (*aux);
}

void remove_inteiro(element_int **head, element_int **aux, int m)
{
    element_int *del;

    while((*aux) != NULL)
    {
        if((*head)->valor == m)
        {
            (*head) = (*head)->next;
            free(aux);
            (*aux) = (*head);
        }

        else if((*aux)->next->valor == m)
        {
            del = (*aux)->next;
            (*aux)->next = del->next;
            free(del);
        }
        (*aux) = (*aux)->next;
    }
}


Baiscally,此打印:

5
4
3
2
1
0
Segmentation Fault


我真的不知道为什么。应该消除数字4,然后再次打印数字。因此,所需的输出为:

5
4
3
2
1
0
5
3
2
1
0


函数insere_inteiro创建一个新元素,而函数remove_inteiro删除一个元素。

列表中的每个元素都有一个称为valor的整数。

最佳答案

您取消引用中的下一个值而不检查是否存在

07-24 09:46
查看更多