Pregunta

Los nodos de lista doblemente enlazados se crean en la función principal.Ender y encabezado definidos.Se rompe en la función de eliminación del nodo: el finalizador es nulo.

¿Cuál es la mejor manera de liberar la memoria de la última y primera entrada, es decir:borrar:233,A y 888,F?

#include <stdafx.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

typedef struct record {
    int idnumber;
    char initial;
    struct record *prevStudent;
    struct record *nextStudent;
} STUDENT;

STUDENT *header = NULL;  //pointer to the start of linked list
STUDENT *ender = NULL;   //pointer to the end of the linked list

void Makenode(int x, char y);
void deletenode();

int main() {
    Makenode(233, 'A');
    Makenode(456, 'H');
    Makenode(746, 'G');
    Makenode(888, 'F');
    deletenode();

    fflush(stdin);
    getchar();
    return 0;
}

void Makenode(int x, char y) {
    STUDENT *ptr;

    ptr = (STUDENT *)malloc(sizeof(STUDENT));
    if (ptr != NULL) {
        ptr->idnumber = x;
        ptr->initial = y;
        ptr->nextStudent = header;
        ptr->prevStudent = NULL;

        if (header == NULL)
            ender = ptr;
        else
            header->prevStudent = ptr;

        header = ptr;

    } else {
        printf("Memory not allocated\n");
    }
}

void deletenode() {
    //delete the first and the last node of the linked list
    STUDENT *p = header, *q = ender;
    char c;

    printf("Are you sure you want to delete Y/N:\n");
    fflush(stdin); c=getchar();
    while (c == 'Y' || c == 'y') {
        ender=ender->nextStudent;
        header=header->prevStudent;
        free(p); free(q);
    }
}   
¿Fue útil?

Solución

Su función de eliminación deja la lista vinculada en un estado ilegal.En todo momento (excepto temporalmente dentro de las funciones de inserción y eliminación), lo siguiente debe ser cierto:

  • Si el header es nulo, el ender también debe ser nulo y la lista está vacía.
  • Si un nodo p tiene un enlace no nulo a p->next, entonces p->next->prev == p.
  • Asimismo, si un nodo p tiene un enlace no nulo a p->prev, entonces p->prev->next == p.
  • El encabezado no tiene ningún nodo anterior;el final no tiene siguiente nodo.

Estas son las invariantes de su lista enlazada.

Si verifica su código para eliminar:

void deletenode()
{
    STUDENT *p = header, *q = ender;

    ender=ender->nextStudent;
    header=header->prevStudent;
    free(p); free(q);
}

puedes ver que acabas de configurar el header y ender a NULL, porque eso es lo que ender->nextStudent y header->prevStudent son.Pero incluso revertir eso no ayudará, porque debe actualizar los enlaces de los nodos adyacentes.

Aquí hay dos funciones, una para cada tarea, que funcionan:

void delete_first()
{
    STUDENT *p = header;

    if (p) {
        if (p->nextStudent == NULL) {
            header = ender = NULL;
        } else {
            p->nextStudent->prevStudent = NULL;
            header = p->nextStudent;
        }
        free(p);
    }
}

void delete_last()
{
    STUDENT *p = ender;

    if (p) {
        if (p->prevStudent == NULL) {
            header = ender = NULL;
        } else {
            p->prevStudent->nextStudent = NULL;
            ender = p->prevStudent;
        }
        free(p);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top