创建列表列表(结构)

时间:2014-11-14 18:36:52

标签: c

我正在做一个编程任务,我还没有完全掌握链接,因为我们还没有完成它。但是我觉得我需要它来做我想要的,因为数组不够用

我创建了一个结构如下

struct node
{
float coef;
int expo;
struct node *link;
};
从这里我可以创建指向每个具有不同名称的结构的指针,但是我遇到的问题是我希望用户输入来确定我构造的数量。我还希望能够添加和创建不同的结构。

2 个答案:

答案 0 :(得分:1)

您需要创建一个头指针来跟踪您的列表。

这可能会有所帮助:

struct list
{
    struct node *head;
    int count;
};

您需要为每个新节点分配内存并将头部移动到新创建的节点。

struct node *add_node(struct list *pList, float coef, int expo)
{
    if (pList == NULL)
    {
        return NULL;
    }

    struct *node pNode = (struct node*)malloc(sizeof(struct node));

    if (node == NULL)
    {
        return NULL;
    }

    pNode->coef = coef;
    pNode->expo = expo;
    pNode->link = pList->head;

    pList->head = pNode;
    pList->count++;

    return pNode;
}

要删除元素,您需要向前移动头部,然后释放它以前的内存。

void *delete_node(struct list *pList, float coef, int expo)
{
    if (pList == NULL)
    {
        return NULL;
    }


    struct node *tmp = pList->head;

    pList->head = pList->head->link;

    free(tmp);

    pList->count--;
}

<强> 注意:

这不是最终版本。我只想指出应该做些什么。

答案 1 :(得分:0)

我会尝试这样的数据结构

struct node
{
    float coef;
    int expo;
    struct node *link;
};

struct poly
{
    node *value;
    struct poly *link
}

维护poly s的链接列表,每个链接列表都包含node s的链接列表。

相关问题