Doubly linked list nodes are created at the main function. Ender and header defined. Breaks at the delete node function- ender is null.
What's the best way to free the memory of the last and first input, i.e.: delete: 233,A and 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);
}
}
while (c == 'y') ...
You never changec
in that loop; if it is entered, it will loop forever. Did you mean to wrap that loop aroundc = getchar()
? – M Oehmheader->prevStudent
andender->nextStudent
beNULL
by definition? – M Oehm