Reputation: 105
I'm trying to write a linked list of Node
objects, where each Node
contains: a string - data
, and a pointer - next
. To manage the list (e.g: add/remove nodes), I have Node
objects: head
, curr
and temp
. I'm trying to work out how to link up each node to the previous one when new data is added to the list, but I am having trouble doing so. The error is occuring in Node.cpp when I am trying to link the new node n
to the curr
nodes next
pointer.
LinkedList.cpp:
#include <iostream>
#include <cstdlib>
#include "LinkedList.h"
#include "Node.h"
using namespace std;
LinkedList::LinkedList(value_type setData) {
head.setData(setData);
cout << head.getData() << endl;
}
void LinkedList::addNode(value_type addData) {
Node n;
n.setData(addData);
if (head.getData() != "") {
curr = head;
while(curr.getNext() != NULL) {
//Still writing this..
}
curr.setNext(n); //Is this correct?
}
else {
head = n;
}
}
LinkedList.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Node.h"
class LinkedList {
public:
typedef std::string value_type;
LinkedList();
LinkedList(value_type setData);
void addNode(value_type addData);
private:
Node head;
Node curr;
Node temp;
};
#endif
Node.cpp:
#include <iostream>
#include <cstdlib>
#include "Node.h"
using namespace std;
Node::Node() {
data = "";
next = NULL;
}
void Node::setData(value_type setData) {
data = setData;
}
string Node::getData() {
return data;
}
void setNext(Node n) {
next = n; //'next' was not declared in this scope error.
//Does this assignment statement even work in this scenario?
}
Node * Node::getNext() {
return next;
}
Node.h:
#ifndef NODE_H
#define NODE_H
class Node {
private:
typedef std::string value_type;
value_type data;
Node* next;
public:
Node();
void setData(value_type setData);
value_type getData();
void setNext(Node n);
Node * getNext();
};
#endif
Any help would be greatly appreciated, thanks guys.
Upvotes: 0
Views: 2171
Reputation: 502
The function void setNext(Node n);
is declared in class Node
. So in Node.cpp
, you must define the function with void Node::setNext(Node n);
. The symbol ::
will show the function's scope.
Upvotes: 0
Reputation: 585
You've got this line:
void setNext(Node n) {
You probably want this instead:
void Node::setNext(Node n) {
Upvotes: 1