c - 从链表中删除最后一个元素

标签 c pointers linked-list

对于一个项目,我需要一个 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/

相关文章:

c - 我正在尝试用 c 计算指数,但这就是得到的

C++ 指针延迟声明语法

c++ - 将指针设置为 NULL 会影响您指向的原始项目吗?

c - 使用指针在 C 中复制多维数组时出现段错误

java - 如何在数组列表中引用数组元素?

c++ - 具有智能指针或原始指针的链表中的节点?

c - 为什么它说我的队列大小为 0?

c - 缺少这个 CRC-CCITT (Initial Value 0xFFFF) Encode 怎么办?

javascript - Javascript 中的链表与数组

c - malloc() 与 free() 相比如何工作