我的作业有问题,它涉及编辑链表。我的代码似乎工作得很好,除了它不删除学生ID=1(或链表中的第一个节点)的数据项。当我试图删除链表上的第一个节点(或者,在main()中删除(1))时,它返回"学生未找到"消息。有人能告诉我出了什么问题吗?谢谢。
/****************************************************************************
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:%fn" , 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);
}
}
问题在于:
for( tempNode = *headerPtr ; tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL ; tempNode = tempNode->nextStudentNode );
你从第二个学生开始检查,而不是第一个学生。因此,您将在没有找到正确ID的情况下到列表末尾。
:我的意思是订单列表。
函数第一个循环中的条件
tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL ;
是错误的,因为它跳过了第一个节点的ID。
函数可以写得更简单
/* Delete student data */
void delete( int inputID )
{
studentNode *prev = NULL;
studentNode *tempNode = head;
while ( tempNode && tempNode->ID != inputID )
{
prev = tempNode;
tempNode = tempNpde->nextStudentNode;
}
if ( tempNode )
{
if ( !prev ) head = tempNode->nextStudentNode;
else prev->nextStudentNode = tempNode->nextStudentNode;
free( tempNode );
}
}