使用不同的构造函数创建链表

问题描述 投票:0回答:1
#include<iostream>
using namespace std;

class node
{
public:
    int data;
    node* next;

    node()                  //default constructor
    {
        data = 0;
        next = NULL;
    }
    node(int value)         //parameterize constructor
    {
        data = value;
        next = NULL;
    }
};


int main()
{
    node* n = new node();   //no argument
    cout<<n->data<<"->";
    node* n1 = new node(1); //1 argument
   cout<<n1->data<<"->";
   node* n2 = new node(2);
   cout<<n2->data;

    cout<<endl;
    cout<<endl;


    return 0;
}

我想用不同的构造函数创建链接列表。我不明白我应该在构造函数中做什么,我给了 next = NULL。问题是我的下一个指针到处都是 NULL。它没有指向任何其他块。

c++
1个回答
0
投票

首先我想强调以下所有答案仅供学习。

在实际代码中,如果您需要链表,我建议使用

std::forward_list
表示单链表,使用
std::list
表示双向链表。

您可以通过其中的第一个节点来表示整个列表,我们将其称为“头”。

可以通过向构造函数添加可选参数以及指向前一个节点的指针来连接节点。

另请注意,在现代 C++ 中,不建议使用手动

new
/
delete
。一种替代方法是使用智能指针。

但是对于这个玩具示例,您甚至不需要智能指针 - 只需分配堆栈上的节点即可。

另一个好的做法是封装数据成员,并允许通过访问器方法访问它们。并使用

nullptr
代替
NULL
(这是 C 的遗产)。

我还添加了一个方法

print_list_starting_from_me
,它从代表头的节点开始打印整个列表。

完整示例:

#include<iostream>

class node
{
public:
    node(node * pPrev = nullptr) 
        : data{ 0 }, next{ nullptr }
    {
        if (pPrev) pPrev->next = this;
    }

    node(int value, node* pPrev = nullptr)
        : data{ value }, next{ nullptr }
    {
        if (pPrev) pPrev->next = this;
    }

    void print_list_starting_from_me() const
    {
        node const * pScan = this;
        while (pScan)
        {
            std::cout << pScan->data << " -> ";
            pScan = pScan->next;
        }
        std::cout << "[END]\n";
    }

    // Accessors to the data:
    int  get_data() const { return data; }
    void set_data(int d)  { data = d; }

private: // encapsulate data members
    int data;
    node* next;
};


int main()
{
    node head;
    node n1{ 1, &head }; // n1 is the next node after head
    node n2{ 2, &n1 };   // n2 is the next node after n1
    head.print_list_starting_from_me();
}

输出:

0 -> 1 -> 2 -> [END]
© www.soinside.com 2019 - 2024. All rights reserved.