结构链接到链表

use*_*281 1 c++ data-structures

我是c ++的新手,我正在尝试将我在python中创建的程序移植到c ++.我有一个结构,它是一个包含部件列表的链表.这些部件中的每一个都包含一个或多个部件.所以我试图创建两个结构,其中一个结构链接到另一个结构.

但我似乎没有得到list_part链接到component_list.

struct list_part {
    char partname[100];
    int parttype;
    component_list * comp;
    list_part * next;
};

struct component_list {
    char compname[100];
    component_list * next;
};
Run Code Online (Sandbox Code Playgroud)

我使用以下函数将部件添加到列表的底部.

void addpart(char partname[], int parttype, component_list *newcomp) {
    struct list_part *temppart;
    struct list_part *currentpart;

    temppart = (struct list_part *)malloc(sizeof(struct list_part));
    strcpy_s(temppart->partname,partname);
    temppart->parttype = parttype;
    temppart->comp = newcomp;

    currentpart = head;

    if (head == NULL) {
        head = temppart;
        head->next = NULL;
    } else {
        while (currentpart->next != NULL) {
            currentpart = currentpart->next;
        }
        temppart->next = NULL;
        currentpart->next = temppart;
    }
}
Run Code Online (Sandbox Code Playgroud)

以及将组件添加到列表的类似功能.

void addcomp(char compname[]) { 
    struct component_list *tempcomp;
    struct component_list *currentcomp;

    tempcomp = (struct component_list *)malloc(sizeof(struct list_part));
    strcpy_s(tempcomp->compname,compname);

    currentcomp = newcomp;

    if (currentcomp == NULL) {
        currentcomp = tempcomp;
        currentcomp->next = NULL;
    } else {
        while (currentcomp->next != NULL) {
            currentcomp = currentcomp->next;
        }

        tempcomp->next = NULL;
        currentcomp->next = tempcomp;
    }
}
Run Code Online (Sandbox Code Playgroud)

当零件中的第一个组件存在时,我尝试添加它.

struct component_list *newcomp = NULL;
strcpy_s(compname,temp.c_str());
addcomp(compname);
Run Code Online (Sandbox Code Playgroud)

我正计划用其他组件添加这些命令

strcpy_s(compname,temp.c_str());
addcomp(compname);
Run Code Online (Sandbox Code Playgroud)

最后,这是作为一部分添加的

addpart(partname,fluidname, parttype, newcomp);
Run Code Online (Sandbox Code Playgroud)

当我这样做时newcomp只返回00000000,但我需要它返回一个指向列表的指针,该指针包含该部分的组件.我不知道如何真正做到这一点,我已经习惯了动态语言,这不是一个问题.我认为这是解决这个问题的最好方法,但我对其他解决方案的建议非常开放.因为数据结构是我非常新鲜的东西.

Alo*_*ave 6

由于你是开放的建议,我认为最好的建议是你应该使用std :: list.而不是你自己的链表实现.

std :: list是C++标准库提供的随时可用的STL容器,它总是比你编写的任何列表实现更有效.

  • 要添加@ SteveJessop的评论,如果效率是目标,那么容器的chioce将根据2个因素而变化:1.要存储在Container中的数据和2.要对数据执行的操作. (2认同)