I am having problems with my homework, which deals with editing linked list. My code seems to work fine, except it does not delete data items with student ID=1 (or the first node in linked list). When I try to delete the first node on the linked list (or, delete(1) within main()), it returns "Student not found" message. Could someone please tell me what went wrong? Thanks.
/****************************************************************************
Date : 12 August 2015
Assignment : Use linked list to build a database of student records, which supports find(), insert() and delete()
****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
/* Define structure studentNode that contains ID, name, GPA and pointer to next studentNode*/
typedef struct student {
int ID;
char *name;
float GPA;
struct student *nextStudentNode;
} studentNode;
/* Initialize header */
studentNode *header;
/* Function prototypes*/
void insert(int ID, char *name, float GPA);
void printList();
void delete(int ID);
/* Main function which runs through while loop until sentinel value of q is typed by user. */
int main() {
insert(3, "John", 3.5);
insert(12, "Smith", 2.8);
insert(1, "Mary", 1.8);
printList();
delete(1); /***** there seems to be a problem here*********/
delete(12);
delete(3);
printList();
return 0;
}
/* Insert new student data */
void insert(int ID, char *name, float GPA) {
studentNode *newStudent = (studentNode*)malloc(sizeof(struct student));
newStudent->ID = ID;
newStudent->name = name;
newStudent->GPA = GPA;
newStudent->nextStudentNode = header;
header = newStudent;
}
/* Run through linked list one by one to print all data items */
void printList() {
studentNode *tempNode;
for (tempNode = header ; tempNode != NULL ; tempNode = tempNode->nextStudentNode) {
printf( "ID:%d name:%s GPA:%f\n" , tempNode->ID, tempNode->name, tempNode->GPA);
}
}
/* Delete student data */
void delete(int inputID) {
studentNode *tempNode;
studentNode **headerPtr = &header;
for (tempNode = *headerPtr ;
tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL;
tempNode = tempNode->nextStudentNode);
studentNode *nodeToDelete = tempNode->nextStudentNode;
if (nodeToDelete->ID != inputID) {
printf("Student not found.\n");
} else {
printf("ID:%d name:%s GPA:%f is deleted.\n" , nodeToDelete->ID, nodeToDelete->name,
nodeToDelete->GPA);
tempNode->nextStudentNode = nodeToDelete->nextStudentNode;
free(nodeToDelete);
}
}