在C++中制作一个简单的链表

Making a simple linked list in C++

本文关键字:一个 简单 链表 C++      更新时间:2023-10-16
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() 应该使用字符串列表中的输入来创建并返回链表。老实说,我有点迷茫。任何帮助将不胜感激。

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

其次,你对一个字符串使用 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;
}
首先

,由于您的temp代表了最后一个元素,因此我会在开头将其放入NULL(nullptr更符合C++的精神,所以我将在下面的文本中使用它)。之后在while循环中,当你添加一个新元素时,你应该写n->next=nullptr,因为新元素的指针next(如果你总是把它添加到列表的后面)将始终指向nullptr。在你的实现中,你的新元素n总是指向自己。稍后在while循环中,您需要检查是否head==nullptr,如果这是真的,则应将head分配给head=n的新元素。如果head不等于nullptr则需要将元素n添加到后面的temp->next=n。在循环的 and 中,您应该将 n 元素指定为 last- temp=n(这必须在 else 块之外,因为它在上述两种情况下都是完成的)。

怕答案首先有一些错误......

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;
}
相关文章: