在C中向不透明链表处理程序追加项

xdnvmnnf  于 2023-02-18  发布在  其他
关注(0)|答案(1)|浏览(89)

我开始在C中使用链表,我发现了一些问题,(如果我理解得很好)在不知道内部结构(字段)的情况下操作链表!
给定一个指向链表的指针,在不知道链表的内部结构**(不透明)的情况下,是否可以在链表中添加/删除一个项**?
编辑(添加详细信息)。
因此,问题是创建一组函数来操作链表,给定链表上的一个句柄作为参数,该参数按以下方式声明:

typedef struct list *handler;

例如我创建了一个函数来创建一个链表:

handler ListCreate()
{
    handler list = (handler)malloc(sizeof(handler));
    if(!list)
    {
        printf("can not allocate memory \n");
        return NULL;
    }
    return list;
}

但是当涉及到附加,我只是阻止,我认为这是不可能做到的,但也许我错了。
这是函数的原型:

int ListAppend(handler list, void *item)
tjjdgumg

tjjdgumg1#

我想做一些类似的事情,但我必须自己解决。想法是创建一个不透明的对象接口,然后通过使用switch语句强制转换来访问实现文件的属性。我这样做是为了遵循依赖反转原则。所有代码都在一个文件中,以显示它可以编译,但三个注解行//interface,//dependency,和//context可以分解为不同的文件,因此您可以尝试依赖文件的不同实现,而不必更改接口文件。

#include <stdlib.h>
#include <stdio.h>

//interface
typedef enum {
    DEP1,
    DEP2
} Type;

typedef struct Interface{
    struct Interface* ptr;
    void* data;
    int (*getConcreteStuff)(struct Interface*, Type t);
} Interface;

//dependency
typedef struct {
    int concreteStuff1;
} Dependency1;

typedef struct {
    int concreteStuff2;
} Dependency2;

static int getConcreteStuff(Interface* interface, Type t) {
    switch(t){
        case DEP1:
            return ((Dependency1*) interface->data)->concreteStuff1;
            break;
        case DEP2:
            return ((Dependency2*) interface->data)->concreteStuff2;
            break;
    }
}

Interface Dependency1_new(Interface* ptr){
    Dependency1* d = malloc(sizeof(*d));
    d->concreteStuff1 = 1;
    struct Interface x = {ptr, d, getConcreteStuff };
    return x;
}

Interface Dependency2_new(Interface* ptr){
    Dependency2* d = malloc(sizeof(*d));
    d->concreteStuff2 = 2;
    struct Interface y = {ptr, d, getConcreteStuff };
    return y;
}

//context
typedef struct {
    Interface i;
} Context;

void Context_doSomething(Context* ctx, Type t){
    printf("%d\n", ctx->i.getConcreteStuff(&ctx->i, t));
}

int main(){
    Context ctx1 = { Dependency1_new(NULL) };
    Context_doSomething(&ctx1, DEP1);
    Context ctx2 = { Dependency2_new(&ctx1.i) };
    Context_doSomething(&ctx2, DEP2);
    Context ctx3 = { *ctx2.i.ptr };
    Context_doSomething(&ctx3, DEP1);
    return 1;
}

相关问题