gpt4 book ai didi

c - 删除链表中的第一个节点

转载 作者:行者123 更新时间:2023-11-30 15:17:46 24 4
gpt4 key购买 nike

我的作业遇到了问题,该作业涉及编辑链接列表。我的代码似乎工作正常,但它不会删除学生 ID=1(或链表中的第一个节点)的数据项。当我尝试删除链表上的第一个节点(或者 main() 中的 delete(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:%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);
}
}

最佳答案

问题在于:

for( tempNode = *headerPtr ; tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL ; tempNode = tempNode->nextStudentNode );

您正在从第二个学生开始检查,而不是第一个学生。因此,您将转到列表末尾而找不到正确的 ID。

更新:我的意思是列表顺序。

关于c - 删除链表中的第一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com