c++ - 实现链表

标签 c++ linked-list

我正在致力于用 C++ 实现链表。虽然我过去在 java 中做过这个,但我不明白如何在 C++ 中用指针来做,因为代码编译但它在我运行它时给我一个段错误。我做错了什么?

我的node.h文件

#ifndef NODE_H
#define NODE_H

#include <string>
using namespace std;

class Node
{
public:

    Node(const string, const int) ;
    ~Node() { }
    void setNext(Node *); // setter for the next variable
    Node * getNext();     // getter for the next variable
    string getKey();      // getter for the key variable
    int getDistance();    // getter for the dist variable

private:
   Node *next;
   int dist;
   string key;
};

#endif

我的 Node.cpp 文件

#include "node.h"
#include <string>

Node::Node(string key, int dist){
    key = key;
    dist = dist;
}

void Node::setNext(Node * next){
    next->next;
}

Node * Node::getNext(){
    return this->next;
}

string Node::getKey(){
    return key;
}

int Node::getDistance(){
    return dist;
}

还有我的 main.cpp 文件

#include "node.h"
#include <iostream>

using namespace std;

int main(){
    Node* nptr1 = new Node("Test1", 2);
    Node* nptr2 = new Node("Test2", 2);
    Node* temp;

    nptr1->setNext(nptr2);
    temp = nptr1->getNext();
    cout << temp->getKey() << "-" << temp->getDistance() << endl;
}

如有任何帮助,我们将不胜感激。 谢谢。

最佳答案

您应该将所有成员初始化为定义的值。您不应该将参数和成员命名为相同的名称,这几乎总是会导致混淆,或者更有可能导致错误

Node::Node(string key_val, int distance)
    : next(0)
{
    key = key_val;
    dist = distance;
}

更好的是,使用成员初始化

Node::Node(string key_val, int distance)
    : next(0),
      key(key_val),
      dist(distance)
{
}

正如评论者已经指出的那样,您必须将 setNext() 中的 next 指针设置为给定参数,并且您应该修改参数,但是 this->next 成员

void Node::setNext(Node * next_ptr){
    next = next_ptr;
}

关于c++ - 实现链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14881809/

相关文章:

c - 双向链表的双重自由错误

c++ - 执行变量原始拷贝的简单转换是否会破坏严格的别名?

C++ 未定义对命名空间中函数的引用

c++ - 一次包含已在 main.obj 中定义的 .h 函数

c++ - 引用指针不适用于 C++ 中的头文件

java - 非常大的 Java ArrayList 遍历时间很慢

c++ - CMAKE - 调试/交叉构建?

c++ - 错误 C3017 : termination test in OpenMP 'for' statement has improper form

c - 单链表输出

c - 从文件中读取并将格式化的行输入到链接列表中。 C