代码之家  ›  专栏  ›  技术社区  ›  Addison

使用结构创建和展开链接列表

  •  1
  • Addison  · 技术社区  · 13 年前

    我一直在C99的一个程序中工作,这个程序主要基于结构。我发现我可以创建结构的链表,并想试一试。

    以下是一个痛苦的尝试,修改了大约50次,目的是做以下事情:

    1) 在主方法中创建一个BASE类型的结构,该结构包含链表(CHAIN)的头。

    2) 将此BASE结构传递给另一个函数,该函数将在链表的末尾附加额外的CHAIN元素。

    3) 打印主要的链表元素,向我自己证明这些更改不仅仅是在其他方法中。

    #include <stdlib.h>
    #include <stdio.h>
    typedef struct Base {
        //many things
        struct Chain *head;
    } BASE;
    
    typedef struct Chain {
        int x;
        struct Chain *next;
    } CHAIN;
    
    void extendChain(BASE *Data, int length);
    
    int main() {
        BASE Data;
        CHAIN *pointer;
        Data.head = 0;
        int length = 10; //userInput(); // gets integer
        extendChain(&Data, length);
        pointer = Data.head;
        while (pointer) {
            printf("%d\n", pointer->x);
            pointer = pointer->next;
        }
    }
    
    void extendChain(BASE *Data, int length) {
        CHAIN *position;
        position = Data->head;
        for (int i=0; i<length; ++i) {
            if (!Data->head) {
                // this will set the first value, the first time this is run.
                Data->head = malloc(sizeof(CHAIN));
                Data->head->x = -1; // set values here. Irrelevant.
                position = Data->head;
            } else if (position) {
                while (position->next) {
                    position = position->next;
                }
                position = malloc(sizeof(CHAIN));
                position->next = 0;
                position->x = i; // placeholder
            }
        }
    }
    

    结果很糟糕,我意识到我的例子甚至在理论上都不起作用(但我已经尽力了)。我开始认为,唯一的方法是用同样的方法来做这一切,我早些时候成功地做到了,但这会很快变得混乱,而且方法肯定是最好的。

    当只传递一个包含链接列表标头的结构时,有人有创造性地将X元素添加到链接列表中吗?非常感谢,一如既往。

    2 回复  |  直到 13 年前
        1
  •  1
  •   Manoj Awasthi    13 年前

    代码中的逻辑错误。此代码有效:

    void extendChain(BASE *Data, int length) {
        CHAIN *position;
        position = Data->head;
        int i;·
        for (i=0; i<length; ++i) {
            if (!Data->head) {
                // this will set the first value, the first time this is run.
                Data->head = malloc(sizeof(CHAIN));
                Data->head->x = -1; // set values here. Irrelevant.
                Data->head->next = NULL; // <========= 
                position = Data->head; 
            } else if (position) {
                while (position->next) {
                    position = position->next;
                }
                CHAIN * position_new_node = malloc(sizeof(CHAIN)); // <========= 
                position_new_node->next = 0; // <========= 
                position_new_node->x = i; // placeholder // <========= 
                position->next = position_new_node; // <========= 
            }
        }
    }
    
        2
  •  0
  •   zed111    13 年前

    算法

    创建原始链接列表 将要添加的链表发送到函数 遍历到第一个链表的末尾(让指针为t) 重复: t旁边的节点=新链表的下一个节点 将两个节点向前移动一个单位 直到新链表的下一个节点为Null