【问题标题】:Is this a correct implementation of remove_from_front in a linked list?这是链表中 remove_from_front 的正确实现吗?
【发布时间】:2015-06-02 04:01:05
【问题描述】:

只是想知道这是否是 remove_from_front 的正确实现。

struct lnode {
    int item;
    struct lnode *next;
};

// remove_from front consumes a linked list that is stored on the heap and removes the first list.
    void remove_from_front(struct lnode **list) {
    struct lnode *next = (**list).next;
    free(*list);
    *list = next;
    }

【问题讨论】:

  • @EOF 我添加了struct lnode的定义:)
  • 这看起来不错,你有问题吗?如果你没有问题,那么这个问题是题外话,可能应该发布在 stackcodereview.com
  • 如果重新排序*list = nextpointerfree(currentpointer)的重置顺序,该函数可能更容易适应并发。
  • 对不起,我有点新堆栈
  • 在使用*list之前检查NULL。

标签: c linked-list heap-memory


【解决方案1】:

就功能而言,它看起来还不错。现在提供一些稳健性提示:

  • 如果列表为空,该函数将出现问题(通常是段错误)。这可能是可取的,但应记录在案。
  • 该函数既不检查上述情况,也不检查最终的NULL 参数。这应该是asserted。

重做:

// Removes the head from a non-empty list whose nodes have been malloc'ed.
void remove_from_front(struct lnode **list) {
    assert(list && "The parameter must not be NULL");
    assert(*list && "The list must not be empty");

    struct lnode *next = (**list).next;
    free(*list);
    *list = next;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2019-09-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多