i'th node on Linked List

closed account (S3TkoG1T)
This is what I have: I'm stuck in actually getting a node at a specific index from the linked list. I don't know how to implement it properly. add() function works fine -- except for get.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;

template<typename T>
class Node {

protected:
struct Nodelist {
	Nodelist *next;
	T val;

	Nodelist(T value1, Nodelist *next1 = NULL) : val(value1), next(next1) {}
};

	Nodelist *head;

public:
	Node() {head = NULL; }
	~Node();
	void add(T val);
	void remove(T val);
	void displayList();
	T& get(int i);
};

template <typename T>
T& Node<T>::get(int i) {
	
	int len = 0;

	Nodelist *temp = head->next;
	
	while((temp = temp->next) != NULL) { 
		if(i == len++)
			return temp;
	}
		return NULL;
	
}

template<typename T>
void Node<T>::add(T val) {

	if(head == NULL)
		head = new Nodelist(val);
	else {
		Nodelist *nodePtr = head;
		while(nodePtr->next != NULL)
			nodePtr = nodePtr->next;
		nodePtr->next = new Nodelist(val);
	}
}


I tried implementing like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

#include "node.h"

using namespace std;


int main () {
	
	Node<int> head;

	head.add(2);
	head.add(3);
	head.add(7);
	head.add(12);

	cout << endl << endl;
	
	cout << endl << "The i'th value: " << endl;
	head.get(2);
	cout << endl << endl;

return 0;
}


But I am getting errors like:

node.h:41:11: error: invalid initialization of reference of type 'int&' from expression of type 'Node<int>::Nodelist*'
node.h:43:10: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'long int'


I would appreciate any help!
Topic archived. No new replies allowed.