【问题标题】:Linked List Parameterized constructor链表参数化构造函数
【发布时间】:2019-04-10 21:26:39
【问题描述】:

我试图为链表做一个参数化构造函数我的程序即将通过使用一个喜欢的列表来实现一个队列所以我想做一个像 Queue(int value , int size) 这样的参数化构造函数并且它不会运行或做一个清单 这是我解决这个问题的代码

Queue(int value,int _size)
    {
        for(int i = 0; i < _size; ++i)
        {
            Node* temp = new Node;
            temp->data = value;
            temp->next = nullptr;
            if(head == nullptr)
            {
                head = tail = temp;
            }
            else
            {
                tail->next = temp;
                tail = temp;

            }
        }
    }

我希望结果是按值乘以大小来填充 lest,就像我运行这个函数 Queue x(20,3) 链接列表应该是 20 20 20

【问题讨论】:

    标签: class c++11 linked-list queue


    【解决方案1】:

    由于这是一个构造函数,headtail 未正确初始化以使用它们。我建议在循环之前添加head = tail = nullptr,看看会发生什么。

    【讨论】:

      【解决方案2】:

      在创建节点后遵循此代码。我希望这会奏效。并且一定要使用 i++ 而不是 ++i,因为后者会使循环的大小为 1 次。

       if(head == NULL)
        head = temp;
      else{
        Node *x;
        x= head;
        while(x->next != NULL)
           x = x->next;
        x->next = temp;
      

      }

      【讨论】:

      • 添加标签会得到更多答案
      猜你喜欢
      • 1970-01-01
      • 2022-09-23
      • 2016-03-05
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2013-09-01
      • 1970-01-01
      相关资源
      最近更新 更多