c - 在 C 中使用链接数据结构时的双指针

标签 c linked-list

我是 C 语言新手,正在练习一些常见数据结构的实现。您能否解释一下为什么在执行列表操作(例如 push_front)时首选双指针,而不是使用包含对 head 引用的 SList 包装器>,以及列表的大小,即下面所示的Java方式。

typedef
struct SListNode
{
    int value;
    struct SListNode* next;
} SListNode;

typedef
struct SList
{
    /* Private members */
    int size;
    SListNode* head;
} SList;

/* API */
typedef
struct SListInterface
{   
    int (*get_size)(SList*);
    bool (*empty)(SList*);
    SListNode* (*push_front)(SList*);
} SListInterface;

/* API Implementation */
int 
get_size(SList* list)
{
    return list->size;
}

bool
empty(SList* list)
{
    return list->head == NULL;
}

SListNode*
push_front(int value, SList* list)
{
    SListNode* node = (SListNode*) malloc(sizeof(SListNode));
    node->value = value;
    node->next = list->head;
    list->head = node;
    list->size++;
}

SList* 
List(void)
{
    SList* list = (SList*) malloc(sizeof(SList));
    list->size = 0;
    list->head = NULL;

    return list;
}

SListInterface*
Interface(void)
{
    SListInterface* interface = (SListInterface*) malloc(sizeof(SListInterface));
    interface->get_size = get_size;
    interface->is_empty = is_empty;

    return interface;
}

最佳答案

这是一个“我们如何设计解决方案”和“我们希望其他人如何访问库”的问题。

这个特定问题可以被视为“抽象”问题。通常,在 OOPS 概念中考虑抽象,但它也是像 C 一样的过程编程的一部分。在 C 语言中,可以使用 static 关键字获得某种程度的抽象。

在这里,没有对错之分。我们可以提供一个包装器,以便访问列表更加抽象,并且只考虑数据,但这也会增加维护包装器的复杂性。另外,由于 C 不支持泛型,因此您需要针对不同的数据类型使用不同的包装器/结构,或者,您需要将数据存储为 void* 并保留列表的类型。

因此,添加包装器可以让用户轻松使用列表,但在开发人员级别维护它会很复杂且容易出错。

关于c - 在 C 中使用链接数据结构时的双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50493607/

相关文章:

java - 删除一个链接如何从链表中删除一个节点?

c++ - 如何解决RemoveAStud()中未删除节点并崩溃的问题

typescript - Typescript 中的 LinkedList 实现

C. 打印出来的不对,目前还没搞清楚原因

c - 两个代码片段有什么区别?

C 函数和数组

c - 如何将字符串C中的每个特定字符替换为另一个?

c++ - 内联函数的概念是什么以及它与宏有何不同?

java - 在LinkedList开头插入的时间复杂度

c - 反向打印链表(或反向填充?)