用C ++制作一个简单的链表

时间:2015-02-01 04:19:43

标签: c++ string linked-list cin

struct Node{
    string val;
    Node* next;
};

Node* makeList ()
{
    string current;
    Node* n;
    Node* head= NULL;
    Node* temp = n;

    while(cin>>current && !cin.fail())
    {
        n = new Node;
        n->val = current;
        temp ->next = n;
        temp = temp -> next;
    }
    n->next = NULL;

    return n;
}

我正在尝试了解链接列表,并且此函数makeList()应该使用字符串列表中的输入创建并返回链接列表。说实话,我有点迷茫。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

首先,您将返回链接列表的最后一个节点。我认为您应该返回头并将其分配给第一个节点。

其次你使用cin.fail()作为我认为不应该完成的字符串。如果数据不匹配,cin.fail()将起作用,对于字符串我认为很少见。

该功能看起来有点像:

Node* makeList ()
{
    string current;
    Node* n;
    Node* head= NULL;
    Node* temp = n;

    while(cin>>current && !cin.fail())
    {
        if(current == "0")
            break;
        n = new Node;
        n->val = current;
        temp ->next = n;
        temp = temp -> next;
        if(!head)
            head = n;
    }
    n->next = NULL;

    return head;
}

答案 1 :(得分:0)

首先,由于你的temp表示最后一个元素,我会在开头将它设置为NULL(nullptr更符合C ++的精神,所以我会在它中使用它来的文字)。 在while循环中,当你添加一个新元素时,你应该写n->next=nullptr,因为新元素的指针next(如果你总是添加它)在列表的后面)将始终指向nullptr。在您的实施中,您的新元素n始终指向自己。在您的while循环中,您需要检查是否head==nullptr,如果这是真的,那么您应该指定head到您创建head=n的新元素。如果head不等于nullptr,则您需要将元素n添加到后面temp->next=n。在循环和循环中,您应该将n元素指定为最后一个 - temp=n(由于在上述两种情况下都已完成,因此必须在else块之外)。

答案 2 :(得分:0)

我害怕答案首先得到了一些错误......

Node *make_link_list_from_input(){
    string value;
    Node *head = nullptr;
    Node *current = nullptr;
    Node *last = nullptr;

    while (cin >> value){
        current = new Node();
        if(head== nullptr){
            head = current;
        }
        if(last!= nullptr){
            last->next=current;
        }
        last=current;
    }
    if(last != nullptr) {
        last->next = nullptr;
    }
    return head;
}