Elenco doppiamente collegato in funzione c / cancellazione del nodo
-
21-12-2019 - |
Domanda
I nodi dell'elenco doppiamente collegati vengono creati nella funzione principale.Ender e intestazione definiti.Le interruzioni all'eliminazione del nodo Elimina è NULL.
Qual è il modo migliore per liberare la memoria dell'ultimo e primo input, I.e.: Elimina: 233, A e 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);
}
}
. Soluzione
La tua funzione Elimina lascia l'elenco collegato in uno stato ilegal. In ogni momento (tranne temporaneamente all'interno delle funzioni di inserimento ed eliminazione), è necessario essere true:
- .
- Se il
header
è nullo, ilender
deve anche essere nullo e l'elenco è vuoto. - Se un nodo
p
ha un collegamento non nullo sup->next
, quindip->next->prev == p
. - Allo stesso modo, se un nodo
p
ha un collegamento non nullo ap->prev
, quindip->prev->next == p
. - L'intestazione non ha nodo precedente; L'ender non ha nodo successivo.
Questi sono gli invarianti della tua lista collegata.
Se controlli il tuo codice per l'eliminazione:
void deletenode()
{
STUDENT *p = header, *q = ender;
ender=ender->nextStudent;
header=header->prevStudent;
free(p); free(q);
}
.
Puoi vedere che hai appena impostato il header
e ender
in NULL
, perché è ciò che ender->nextStudent
e header->prevStudent
sono. Ma anche in inverno che non ti aiuterà, perché è necessario aggiornare i link dei nodi adiacenti.
Ecco due funzioni: uno per ogni attività - che funziona:
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);
}
}
.