对于一个项目,我需要一个 C 语言的链表实现,它使我能够删除最后一个元素。
但是,我不知道如何实现这一点。 想法是创建一个函数 (deleteLast),它迭代列表直到下一个元素的下一个为 NULL(因此直到到达倒数第二个元素),然后释放对最后一个元素的引用。
但是,在尝试编译时出现错误“表达式必须具有指向结构或 union 类型的指针”。
#include <stdio.h>
#include <stdlib.h>
struct cell{
int x_coord,y_coord;
struct cell *next;
} cell;
struct cell AddToList (struct cell *list, int x,int y);
int listlength(struct cell * list);
void deleteLast(struct cell **list);
struct cell AddToList(struct cell *list,int x,int y){
struct cell *new_cell;
new_cell = malloc(sizeof(struct cell));
new_cell->x_coord=x;
new_cell->y_coord=y;
printf("Added new coordinates %i %i",x,y);
}
int listlength(struct cell *list){
int i=0;
while(list->next != NULL){
i++;
}
return i;
}
//takes a pointer as reference, because in C parameters are given as values
//see: https://stackoverflow.com/a/35021864
//calls should look like deleteLast( &list )
void deleteLast(struct cell **list){
struct cell *currentcell = *list;
while(*list->next->next != NULL){ //expression must have pointer-to-struct-or-union type
//free list->next
}
}
哪里出错了?
最佳答案
void deleteLast(struct cell **list){
struct cell * currentcell = *list;
while(currentcell->next->next != NULL) {
currentcell = currentcell->next;
}
free(currentcell->next);
}
关于c - 从链表中删除最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55925725/