c++ - Implementing a Linked List -
i working on implementing linked list in c++. while have done in java in past, not understand how in c++ pointers, code compiles giving me segmentation fault when run it. doing wrong?
my node.h file
#ifndef node_h #define node_h #include <string> using namespace std; class node { public: node(const string, const int) ; ~node() { } void setnext(node *); // setter next variable node * getnext(); // getter next variable string getkey(); // getter key variable int getdistance(); // getter dist variable private: node *next; int dist; string key; }; #endif
my node.cpp file
#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(){ homecoming this->next; } string node::getkey(){ homecoming key; } int node::getdistance(){ homecoming dist; }
and main.cpp file
#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; }
any help appreciated. thanks.
you should initialize members defined value. shouldn't name parameters , members same, leads confusion or, more likely, bugs
node::node(string key_val, int distance) : next(0) { key = key_val; dist = distance; }
better yet, utilize fellow member initialization
node::node(string key_val, int distance) : next(0), key(key_val), dist(distance) { }
as commenters pointed out, must set next
pointer in setnext()
given parameter , should not modify parameter, this->next
fellow member
void node::setnext(node * next_ptr){ next = next_ptr; }
c++ linked-list
No comments:
Post a Comment