【问题标题】:Making a simple linked list in C++用 C++ 制作一个简单的链表
【发布时间】:2015-02-01 04:19:42
【问题描述】:
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() 应该使用来自字符串列表的输入来创建和返回链表。老实说,我有点迷路了。任何帮助将不胜感激。

【问题讨论】:

    标签: c++ string linked-list cin


    【解决方案1】:

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

    其次,您将 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;
    }
    

    【讨论】:

      【解决方案2】:

      首先,由于您的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 块之外,因为它在上述两种情况下都完成了)。

      【讨论】:

        【解决方案3】:

        恐怕最重要的答案有一些错误......

        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;
        }
        

        【讨论】:

          猜你喜欢
          • 2011-09-17
          • 1970-01-01
          • 1970-01-01
          • 2011-01-29
          • 1970-01-01
          • 2010-11-08
          • 1970-01-01
          • 2011-11-10
          相关资源
          最近更新 更多