元素未添加到链表

Elements not being added to Linked List

本文关键字:链表 添加 元素      更新时间:2023-10-16

我在元素未添加到我的链表中时遇到问题。我已经能够验证 char 字符串是否在 main() 中正确扫描并复制到临时节点,但这没有添加到链表中。

struct node{
    char string[MAX_STRING_LENGTH];
    node *next;
};
void insertAsFirstElement(node *head, node *last, char string[MAX_STRING_LENGTH])
{
    //create temporary node
    node *temp = new node;
    printf("The temp's string before copy is %s.n", temp->string);
    //this is the string copy from the user to the temp
    strcpy(temp->string, string);
    printf("The temp's string is %s.n", temp->string);
    //set the next pointer to NULL (points to nothing)
    temp->next = NULL;
    //set first value in list to temp
    head = temp;
    //set last value to temp
    last = temp;
}
//this is the string copy from temp to new
char *strcpy(char *temp, const char string);

这将声明strcpy函数。你想称呼它。

strcpy(temp->string, string);

请不要混合搭配 C 和 C++。它们是非常不同的语言。如果您想在C++中执行此操作,那么它非常容易。

#include <string>
#include <list>
int main() {
    std::list<std::string> strings;
    char choice = menu();
    while (choice != '4') {
        switch (choice) {
        case '1':
            std::string input;
            std::cout << "Please enter a string: ";
            std::cin >> input;
            strings.push_back(input);
            break;
        case '2':
            strings.pop_front();
            break;
        case '3':
            if (strings.size() == 0) {
                std::cout << "The list is empty.n";
            } else {
                for (auto &s : strings) {
                    std::cout << s << "n";
                }
            }
            break;
        default:
            std::cout << "System Exit";
            return 0;
        }
    }
}

您发布的代码存在一些问题。

第一个是你的链表不包含字符串,它包含一个指针数组。

您应该省略char *string[MAX_STRING_LENGTH];中的*

第二个是你对scanf的呼唤。

scanf("%sn", &string[MAX_STRING_LENGTH]);

这会将程序用户的输入放入字符串后面的内存中。那不是你想要的。您希望用户的输入在字符串的开头进入内存,如下所示:

scanf("%sn", &string[0]);

或者写得更简单:

scanf("%sn", string);

最后,您不会将字符串复制到链表。您可以使用 strcpy 来做到这一点,如下所示:

strcpy(temp->string, string);