【发布时间】: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