我正在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