我是 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/