【问题标题】:Problem my linked list问题我的链表
【发布时间】:2011-04-06 13:22:36
【问题描述】:

我正在做这个作业任务,它需要我接收一个大字符串,并将其分解为许多子字符串,其中每个字符串由字符串中的 '\n' 新行值指示,并将其存储到一个链表,例如:

string = "hello world\n i need help!!"

会变成:

string1 = "hello world\n"
string2 = "i need help!!"

我已经编写了这段代码,它将字符串分解为子字符串并将它们存储到各个节点中。代码本身非常丑陋,需要更多改进,但我什至无法达到这一点,因为中间似乎发生了奇怪的地方,链表中的所有字符串都被我添加到的最后一个字符串替换链表...

这是我的代码,如果可以的话请帮忙:

#define eq(A, B) ( A == B )

typedef struct list * link;
typedef char Item;

struct list {
    link next;
    Item *string;
};


void printlist (link ls);
link newLS (char text[]);
link newNode (char text[]);
void insertNode (link next, Item item[]);

link newLS (char text[]) {
    int i = 0;
    int j = 0;
    char temp[(strlen(text))];
    link new = NULL;

    while (text[i] != '\0') {
        temp[j] = text[i];
        if (text[i] == '\n' || text[i+1] == '\0') {
            temp[j+1] = '\0';
            j = -1;
            if (new == NULL) {
                new = newNode(temp);
                printf("new: %s", new->string);
            } else {
                insertNode(new, temp);
                printf("new: %s", new->next->string);
            }
        } 
        i++;
        j++;
    }
    printlist(new);
    return new;
}

link newNode (char text[]) {
    link new = malloc(sizeof(*new));
    assert(new != NULL);
    new->string = malloc ((strlen(text)) * sizeof(char));
    new->string = text;
    new->next = NULL;

    return new;
}

void insertNode (link ls, Item item[]) {
    assert (ls != NULL);
    assert (item != NULL);

    while (ls->next != NULL) {
        ls = ls->next;
    }
    ls->next = newNode(item);

}

int main(int argc, char **argv) {
    link ls;

    ls = newLS("1\n2\n3");
    return 0;
}

我们必须使用这个函数:

link newLS (char text[]) 

【问题讨论】:

  • 你能把这个例子缩减成一小段代码,但仍然显示同样的问题吗?这里的人更容易为您提供帮助,并且作为奖励,您可能会自己发现问题的根源(或至少了解更多有关问题的原因)。
  • 下次请为作业添加作业标签。
  • 看到一个名为new的变量后,我觉得很脏。是的,它是 C,new 不是关键字,但仍然是。
  • 好的,下次再做! TB newTB 中的问题线
  • 至少一个承认这是家庭作业并试图解决它的人;)

标签: c linked-list


【解决方案1】:
  1. #define eq(A, B) ( A == B ) 不是一个好主意,改进方法是将其定义为#define eq(A, B) ( (A) == (B) )

  2. 您分配缓冲区,然后,不使用它,而是为该指针分配另一个指针:

    new->string = malloc ((strlen(text)) * sizeof(char));
    new->string = text;
    

    相反,您应该从给定的指针复制数据:

    new->string = malloc ((strlen(text) + 1) * sizeof(char));
    memcpy(new->string, text, strlen(text) + 1);
    

    此外,当您尝试free 分配的内存时,您会遇到分段错误,因为new->string 没有指向分配的区域...

【讨论】:

    【解决方案2】:

    大声笑你使用的是什么编译器!您将变量命名为“新”

    不管怎样,

    您正在重写已传递给节点初始化程序的 char*。 因此,首先您创建了一个带有 temp = "1" 的 newNode(temp),然后在下一次迭代中用值 "2" 覆盖了 temp。

    解决方法:

    new = newNode(temp);

    在上面一行之后插入这个--> temp = new char[strlen(text)];

    插入节点(新,临时);

    在上面一行之后插入这个--> temp = new char[strlen(text)];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2021-01-13
      相关资源
      最近更新 更多