我正在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;
}
任何帮助将不胜感激。 谢谢。
你的'setNext'函数不会做任何事情...... – Mat 2013-02-14 18:42:36
'this.next = next;'? – Kevin 2013-02-14 18:43:31
list <>或slist <>是在C++中使用它的正确方法。只有在C,你必须像这样弄脏你的双手...... – 2013-02-14 18:44:16