C编程: How to pop last element on linked list?

标签 c linked-list

我是一名初学者程序员,一周前有人向我介绍了链表,但我仍然在努力理解这一点。

目前正在尝试编写一个函数来帮助我从链接列表中删除最后一个元素。我希望得到一些解释我在这里做错了什么。感谢您的任何建议。

我不允许触摸或修改当前结构

这是我的结构:

typedef struct node {
    ElemType val;
    struct node *next;
} NODE;

struct list_struct {
    NODE *front;
    NODE *back;
};

这是我当前的代码:

如果列表为空,我们什么都不做并返回任意值 否则,列表中的最后一个元素将被删除,并且它的 返回值。

ElemType lst_pop_back(LIST *l) {


    NODE * p = l->front;
    NODE * trail = l->front;


    if( p == NULL) return 0;

    if( lst_len(l) == 1){
        free(p);
        l->front = NULL;
        l->back = NULL;
    }
    else{
        p=p->next;

        while( p != NULL){

            if( p->next == NULL) free(p);

            trail = trail->next;
            p=p->next;
        }
        trail= trail->next;
        trail->next= NULL;

    }
    return 0;
}

我在 MAC 上使用 Xcode,得到的错误是:Thread 1: EXC_ACCESS(code=1, address=0x8)

最佳答案

XCode 错误 EXC_BAD_ACCESS(code=1, address=0x8) 意味着有人试图访问无法访问的内存。 XCode 的边界检查据说很好,所以让我们相信它们。有点遗憾的是,OP 没有告诉我们确切的行号,但我们可以猜测。我同意 Katerina B. 的观点,并假设与罪魁祸首相同。

详细:

ElemType lst_pop_back(LIST * l)
{
  // p and trail point to the first node
  NODE *p = l->front;
  NODE *trail = l->front;

  if (p == NULL)
    return 0;

  if (lst_len(l) == 1) {
    free(p);
    l->front = NULL;
    l->back = NULL;
  } else {
    p = p->next;
    // Now: trail->next points to the old p
    // and p to p->next, that is: trail points
    // to the node before p

    // while trail is not the last node
    while (p != NULL) {
      // if p is the last node
      if (p->next == NULL){
        // release memory of p, p points to nowhere from now on
        free(p);
      }
      // Following comments assume that p got free()'d at this point

      // because trail points to the node before p
      // trail->next points to the node p pointed to
      // before but p got just free()'d
      trail = trail->next;
      // p got free()'d so p->next is not defined
      p = p->next;
    }
    // assuming p got free()'d than trail->next is one step
    // further into unknown, pardon, undefined territory
    trail = trail->next;
    trail->next = NULL;

  }
  return 0;
}

关于C编程: How to pop last element on linked list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38733515/

相关文章:

c - 动态 C - 字符指针、strcpy、strcat

c++ - 嵌入式系统的 map 文件解释教程

c - 对平方数字求和时是否需要明确处理负数或零?

c++ - 池类抛出错误

java - 如何从对象的 LinkedList 以及所有这些对象的 LinkedList 中删除对象?

无法理解为什么 c 中的 malloc 函数会如下所述执行操作?

c - C中的Inotify事件

java - LinkedList - 循环不工作 - Java

python - SQLAlchemy 和 MySQL 的多重链表

go - 为什么此链表未添加新节点?