我的功能是假设删除我的 Linked_list 中的最后一个节点,每个节点都有一个项目编号和一个年龄。但是当我调用我的函数并显示我的 Linked_list 时,该函数仅将项目编号设置为零,并且假设删除时年龄保持不变。
void deleteLastNode(Record * & head){
Record *temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
delete temp;
return;
};
//my output item number item age
//before the calling the function: 1st node 5000 1
// 2nd node 6753 8
//after calling the delete function: 1st node 5000 1
// 2nd node 0 8
//desired output
//before the calling the function: 1st node 5000 1
// 2nd node 6753 8
//after calling the delete function: 1st node 5000 1
最佳答案
我认为您应该沿着列表向下走,直到到达倒数第二个 节点,然后将该节点指向NULL
并删除最后一个节点。我还认为更改您的函数以返回对列表新头部的引用是有意义的。
Record* deleteLastNode(Record* & head) {
Record* temp = head;
// for an empty list, just return NULL
if (head == NULL) return NULL;
// for a list one just one element, delete the head, and return NULL
if (temp->next == NULL) {
delete temp;
head = NULL;
return head;
}
// otherwise walk down the list until reaching the second to last element
while (temp->next->next != NULL) {
temp = temp->next;
}
delete temp->next;
temp->next = NULL;
// return the head of list with its final node removed
return head;
}
关于c++ - 链表中的节点最后没有删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48435634/